Reputation: 183
Stackoverflow!
I'm usign Laravel. The question is about relations in Eloquent.
Item might have 1 or more than 1 types.
Item.php:
public function types()
{
return $this->hasMany('App\Type');
}
Type.php:
public function items()
{
return $this->belongsToMany('App\Item');
}
Item table:
id
name
Type table:
id
name
The question
I have 4 types. Item №1 has 2 types, Item №2 has 1 type. How should I store item types in database?
Upvotes: 2
Views: 609
Reputation: 163748
You need to define two belongsToMany()
relationships. In the Item
model:
public function types()
{
return $this->belongsToMany('App\Type');
}
And in the Type
model:
public function items()
{
return $this->belongsToMany('App\Item');
}
Also, create the item_type
pivot table.
To work with this many-to-many relationship use the attach()
, detach()
and sync()
methods.
Upvotes: 1