php - Laravel 4 eloquent pivot table -
i have 3 tables: users, items , user_items. user has many items , item belongs 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 pivot (user_items) table i've important column named "equipped".
i've form users can equip, unequip , throw items. form has hidden field pivot (user_items) table row id. so, when user tries equip item, system checks if item equipable.
so, want object pivot data , item data, based on item_id pivot table, can send handler (where logic handled).
so i've first access pivot table , access item table.
something (does not work):
$item = user::find(1)->items->pivot->find(1);
is possible do?
you first have include 'equipable' on pivot call:
return $this->belongstomany('user', 'user_items') ->withpivot('equipable');
then can ask eloquent if item equipable or not:
$item = user::with('items')->get()->find(1)->items->find(2)->pivot->equipable;
keep 2 things in mind:
- eloquent uses 'items' key internally, might interfere.
- whatever method put before "get()" part of db query. after "get()" handled php on object. latter slower in cases.
Comments
Post a Comment