Ad

Save MorphOne Polymorphic In Database

- 1 answer

Using Laravel 5, I got a module class (an Eloquent model). I would like to create subclasses for many kind of module : moduleA, moduleB, etc. Each sub-module have specific attributes and main module class own general attributes. A module belongsTo a Page.

class Module extends Eloquent {

    protected $fillable = ['name', 'slug', 'x', 'y'];

    /*...*/

    public function page()
    {
        return $this->belongsTo('App\Models\Page');
    }
}

class ModuleA extends Module {
    protected $fillable = ['power'];
    /*...*/
}

class ModuleB extends Module {
    protected $fillable = ['size'];
    /*...*/
}

In the database SubModules should have all Module attributes and SubModules attributes. Exemple for Module B : 'name', 'slug', 'x', 'y', 'size' and ModuleB should belongsTo a Page.

What is the best way to implement this kind of classes ?

Updade : How can I do to save everything in MySQL ?

class Module extends Eloquent {

    protected $fillable = ['name', 'slug', 'x', 'y'];

    /*...*/

    public function page()
    {
        return $this->belongsTo('App\Models\Page');
    }
   public function modulable()
   {
        return $this->morphTo();
   }
}

class ModuleA extends Module {
    protected $fillable = ['power'];
    public function module()
    {
        return $this->morphOne('App\Models\Module', 'modulable');
    }
}

Doing a simple $module.save() doesn't store datas of Module and ModuleA (only timestamps) :

$module = new ModuleA();
$m->save(); // 

> db.module_navs_collection.find();
{ "_id" : ObjectId("56a4a4c6bffebcec068b456a"), "updated_at" : ISODate("2016-01-24T10:17:42.097Z"), "created_at" : ISODate("2016-01-24T10:17:42.097Z") }
Ad

Answer

If you want to extend a 'base' model/table I recommend to use the Polymorphic Relations of Laravel.

You have one base model/table ('name', 'slug', 'x', 'y','ref to page', 'ref to extend') and some other with the extended data ('power'|'size'|...).

Ad
source: stackoverflow.com
Ad