Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 eloquent pivot table

I have three tables: users, items and user_items. A user has many items and a item belongs to many users.

The tables:

Users
id
username
password

Items
id
name
equipable

User_items
id
user_id
item_id
equipped

The models:

class User extends Eloquent {
     public function items()
     {
         return $this->belongsToMany('Item', 'user_items')
                   ->withPivot('equipped');
     } 
}

class Item extends Eloquent {
    public function users()
    {
         return $this->belongsToMany('User', 'user_items');
    }
}

In the pivot (user_items) table I've a very important column named "equipped".

I've a form where users can equip, unequip and throw items. This form has a hidden field with the pivot (user_items) table row id. So, when a user tries to equip an item, the system checks if the item is equipable.

So, I want a object with the pivot data and the item data, based on item_id from the pivot table, I can send to the handler (where all logic is handled).

So what I've to do is to first access the pivot table and then access the item table.

Something like this (does not work):

$item = User::find(1)->items->pivot->find(1);

Is this possible to do?

like image 897
Martin Avatar asked May 14 '13 18:05

Martin


1 Answers

You first have to include 'equipable' on your pivot call:

return $this->belongsToMany('User', 'user_items')
             ->withPivot('equipable');

Then you can ask Eloquent if your item is equipable or not:

$item = User::with('items')->get()->find(1)->items->find(2)->pivot->equipable;

Keep two things in mind:

  1. Eloquent uses 'items' as a key internally, so that might interfere.
  2. Whatever method you put before "get()" is part of the db query. Everything after "get()" is handled by PHP on the Object. The latter will be slower in most cases.
like image 59
Ronald Hulshof Avatar answered Oct 03 '22 04:10

Ronald Hulshof