2016-01-23 97 views
1

使用Laravel 5,我得到了一個模塊類(一個Eloquent模型)。我想爲許多類型的模塊創建子類:moduleA,moduleB等。每個子模塊都有特定的屬性和主模塊類自己的通用屬性。一個模塊屬於一個頁面。在數據庫中保存morphOne多態

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']; 
    /*...*/ 
} 

在數據庫中,子模塊應具有所有模塊屬性和子模塊屬性。模塊B的例子:'name','slug','x','y','size'和ModuleB應該屬於一個Page。

實現這種類的最好方法是什麼?

Updade:我該如何保存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'); 
    } 
} 

做一個簡單的$ module.save()不存儲模塊和ModuleA的DATAS(只時間戳):

$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") } 

回答

1

如果你想擴展一個 '基地' 的模式/表我建議使用Laravel的Polymorphic Relations。你有一個基本模型/表('name','slug','x','y','ref to page','ref to extend')和其他一些擴展數據('power '|' 大小'| ...)。

+0

它的工作原理!但是模塊表是空的嗎?只有ModuleA表填充所有數據(我正在使用mongodb) – Ludovic

+0

要解決保存問題,請看下面的答案 – Ludovic

1

要在數據庫保存

接受的答案是很好的一個表結構,而是拯救你需要這樣進行DATAS:

$module = new Module(); 
$module->name = "Generator"; 
$module->save(); 

$moduleA = new ModuleA(); 
$moduleA->power = "120v"; 
$moduleA->save(); 

$moduleA->module()->save($module); 

文件是關於很差。