我有一個名爲Item
的通用模型和一個名爲Itemproperties
的相關模型。動態表格的雄辯模型?
物品 - > hasOne - > Itemproperties
Itemproperties - >屬於關聯 - >項目
的Item
模型有一個名爲 'itemtype_id' 它告訴存儲到哪個表的模型屬性。例如:itemtype = 1,那麼對於itemtype = 2,表是itemproperties_1,則表是itemproperties_2。
所以我改變了getTable()方法的Itemproperties型號:
function getTable(){
return 'item_properties_' . $this->itemtype_id;
}
因此,創建一個新的項目和它的屬性時,我已經設置了Itemproperties這樣的:
// Create & Save the Item
$item = new Item(['itemtype_id' => $itemtype_id]);
$item->save();
// Save the Properties
$itemProperties = new ItemProperties($properties);
$itemProperties->itemtype_id = $item->itemtype_id;
$item->properties()->save($itemProperties);
這似乎工作正常......當保存Itemproperties。
但是,當我嘗試檢索它們時,通過執行$item->properties
,我沒有辦法告訴它itemtype_id,因此無法找到正確的表。
我的問題: 有沒有辦法建立雄辯的關係,以便我可以將item-> itemtype_id傳遞給Itemproperties,以便它知道要使用哪個表?
或者是否有更好的整體策略來完成我正在使用不同的表格爲不同的項目類型?
好的基於最後一個問題,我想到的第一件事是'變形',即你之前考慮過這種多態關係嗎? https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations反正你可以使用這個功能? –
感謝您的建議@OmisakinOluwatobi。我不認爲這會適合我所做的事情,因爲我會有很多不同類型的項目,每個項目都有不同的數量和組合。 – BizzyBob
所以如果我找到你的權利,你的意思是在一個屬性中的列與另一個屬性中的列不同。說屬性a有,Z和Y列,屬性b可以有Z,Y和K列? –