2

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?

Roman Khegay
  • 173
  • 2
  • 16

1 Answers1

1

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.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Ok, Thank you for answer. I looked at [this laraveldaily tutorial](http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/). Should I declare pivot table? `return $this->belongsToMany('App\Item', 'items_types');` – Roman Khegay Feb 28 '18 at 11:40
  • 1
    @rikoart if you're following [Laravel naming conventions](https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions) described in my repo, you can just use `item_type` pivot table. If you want to use another name for the table, you need to define it in both relationships. – Alexey Mezenin Feb 28 '18 at 11:42