[英]Using pivot model data as a relationship to another model in Laravel 4's Eloquent
[英]Eloquent Relationship without Pivot Model
我有3张桌子:
customer
: fields: id, name
item
: fields: id, name
customer_items
: fields: customer_id, item_id, qty
正如我们所期望的那样, Customer
和Item
有他们单独的模型。
问题:如果没有枢轴模型,我将如何将这两个(客户和项目)联系起来。
我想使用$customer->items
直接获取客户项目,而不是执行$customer->customerItem->items
,因为我不想逐个跟踪 customerItems 和客户,因此我认为这是不必要的。
此外,我不能直接将customer_items
表用于Item
模型,因为我可能需要检索其控制器中的所有项目。
正如@kerbholz 所指出的(但他们没有创建答案,所以在这里),在您的客户模型中,您需要以下功能:
public function items()
{
return $this->belongsToMany('App\Item');
}
假设您的 Item 模型类位于App
。 你也可以在你的项目模型中做相反的事情。
现在您应该能够执行$customer->items
并获取项目集合。 如果要包含qty
字段,则需要:
public function items()
{
return $this->belongsToMany('App\Item')->withPivot('qty');
}
请注意,您仍然需要数据透视表,您无法逃避它,但您现在可以以更优雅的方式导航它。
创建customer_items
表并包含custmer_item_id
和user_id
。 在User
模型中包含此功能
public function basket() // example
{
return $this->belongsToMany(User::class, 'customer_items', 'user_id', 'custmer_item_id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.