[英]Eloquent ORM | Laravel's hasMany (more than 1) relation
Stackoverflow!堆栈溢出!
I'm usign Laravel.我正在使用 Laravel。 The question is about relations in Eloquent.
问题是关于 Eloquent 中的关系。
Item might have 1 or more than 1 types.项目可能有 1 种或 1 种以上。
Item.php:项目.php:
public function types()
{
return $this->hasMany('App\Type');
}
Type.php:类型.php:
public function items()
{
return $this->belongsToMany('App\Item');
}
Item table:物品表:
id
name
Type table:类型表:
id
name
The question问题
I have 4 types.我有4种类型。 Item №1 has 2 types, Item №2 has 1 type.
项目 №1 有 2 种类型,项目 №2 有 1 种类型。 How should I store item types in database?
我应该如何在数据库中存储项目类型?
You need to define two belongsToMany()
relationships.您需要定义两个
belongsToMany()
关系。 In the Item
model:在
Item
模型中:
public function types()
{
return $this->belongsToMany('App\Type');
}
And in the Type
model:在
Type
模型中:
public function items()
{
return $this->belongsToMany('App\Item');
}
Also, create the item_type
pivot table.此外,创建
item_type
数据透视表。
To work with this many-to-many relationship use the attach()
, detach()
and sync()
methods.要处理这种多对多关系,请使用
attach()
、 detach()
和sync()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.