【发布时间】:2017-07-28 06:08:04
【问题描述】:
我有一个名为 Item 的通用模型和一个名为 Itemproperties 的相关模型。
Item -> hasOne -> Itemproperties
Itemproperties -> belongsTo -> Item
Item 模型有一个名为“itemtype_id”的属性,它告诉模型要存储到哪个表。例如:itemtype = 1,那么 table 是 itemproperties_1 对于 itemtype = 2,那么 table 是 itemproperties_2。
所以我更改了 Itemproperties 模型上的 getTable() 方法:
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,因此它找不到正确的表。
我的问题: 有没有办法建立 eloquent 关系,以便我可以将 item->itemtype_id 传递给 Itemproperties,以便它知道要使用哪个表?
或者是否有更好的整体策略来完成我正在做的事情,使用不同的表来处理不同的项目类型?
【问题讨论】:
-
好吧,基于最后一个问题,我首先想到的是
morph,即多态关系你之前考虑过这个吗? laravel.com/docs/5.4/…无论如何你都可以使用这个功能吗? -
感谢@OmisakinOluwatobi 的建议。我认为这不适合我正在做的事情,因为我将拥有许多不同类型的项目,并且每个项目都有不同的列数和组合。
-
因此,如果我理解正确,您的意思是一个属性中的列与另一个属性中的列不同。说属性 a 有 Z 和 Y 列,属性 b 可以有 Z、Y 和 K 列?