【问题标题】:Eloquent Model with dynamic table..?具有动态表的雄辩模型..?
【发布时间】: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 列?

标签: laravel laravel-5


【解决方案1】:

您不应该真的需要多个表来解决这个问题。在 Item 和 Properties 之间建立关系就足够了。这意味着在Item 模型中,您应该已经指定在与Property 建立关系时要使用的列

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

这表示itemtype_id在items表中,这里假设Property model中的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 在构建查询并引用时已被传递。这意味着,如果您想检索属性,您只需找到具有其类型 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();

唯一的方式我可能是错的,如果您的不同属性中的字段不同和/或我完全误解了这个问题,但通常您不需要多个表。

【讨论】:

  • 再次感谢您的努力。您说得对,Item 和 Properties 之间存在一对一的关系,但在我的情况下,每种项目类型都可以具有截然不同的属性。例如:项目 #1 可能是一个客户记录,其中包含以下字段:company_name、contact_name、contact_phone;而第 2 项可能是具有以下字段的销售机会:描述、价值、后续日期。我需要所有项目在 Items 表中都有记录,但是由于字段/列的差异,属性需要存储在不同的表中。这有意义吗?
  • @BizzyBob 你找到解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2017-08-03
相关资源
最近更新 更多