2017-07-27 53 views
0

我有一個名爲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,以便它知道要使用哪個表?

或者是否有更好的整體策略來完成我正在使用不同的表格爲不同的項目類型?

+0

好的基於最後一個問題,我想到的第一件事是'變形',即你之前考慮過這種多態關係嗎? https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations反正你可以使用這個功能? –

+0

感謝您的建議@OmisakinOluwatobi。我不認爲這會適合我所做的事情,因爲我會有很多不同類型的項目,每個項目都有不同的數量和組合。 – BizzyBob

+0

所以如果我找到你的權利,你的意思是在一個屬性中的列與另一個屬性中的列不同。說屬性a有,Z和Y列,屬性b可以有Z,Y和K列? –

回答

0

你不應該真的需要多個表來解決這個問題。項目和屬性之間的關係應該足夠。這意味着Item模型,你應該已經指定列建立關係時使用與Property

public function property() 
{ 
    return $this->hasOne(Property::class, 'itemtype_id', 'itemtype_id') 
} 

這意味着itemtype_id在items表,這裏的假設是,itemtype_id物業造型獨特(一個 - 到 - 一個)

然後當你保存一個新的屬性:

$item = new Item(['itemtype_id' => $itemtype_id]); 
$item->save(); 
//then saving properties 
$item->property()->save($properties); //assuming you already have $properties. 

itemtype_id構建查詢時,已經過去了,[R eferences。這意味着如果你想找回你只是櫃面你與它的類型ID找到一個項目的屬性:

$item = Item::where('itemtype_id', 1)->first(); 
//get the properties 
$properties = $item->property; 
//or simply get the properties by calling the Property model directly: 
Property::where('item_property', 1)->first(); 

唯一方式我可能是錯的,如果在你的不同性質領域的變化和/或I完全誤解了這個問題,但通常你不需要多個表。

+0

再次感謝您的努力。你是正確的,項目和屬性之間有一對一的關係,但在我的情況下,每個項目類型可以有很大不同的屬性。例如:項目#1可以是客戶記錄,其中包含以下字段:company_name,contact_name,contact_phone;而項目#2可能是一個帶有字段的描述,價值,followup_date的銷售機會。我需要所有項目在Items表中有記錄,但由於其字段/列的不同,屬性需要存儲在不同的表中。那有意義嗎? – BizzyBob

+0

@BizzyBob你找到解決方案嗎? –