Laravel 4 eloquent 数据透视表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16550761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 eloquent pivot table
提问by Martin
I have three tables: users, items and user_items. A user has many items and a item belongs to many users.
我有三个表:users、items 和 user_items。一个用户有很多物品,一个物品属于很多用户。
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".
在数据透视表 (user_items) 中,我有一个非常重要的列,名为“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.
我有一个表格,用户可以在其中装备、取消装备和投掷物品。此表单有一个隐藏字段,其中包含数据透视表 (user_items) 表行 ID。因此,当用户尝试装备某个物品时,系统会检查该物品是否可装备。
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).
所以,我想要一个包含数据透视表数据和项目数据的对象,基于数据透视表中的 item_id,我可以发送到处理程序(处理所有逻辑)。
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?
这有可能吗?
回答by Ronald Hulshof
You first have to include 'equipable' on your pivot call:
您首先必须在数据透视调用中包含“equipable”:
return $this->belongsToMany('User', 'user_items')
->withPivot('equipable');
Then you can ask Eloquent if your item is equipable or not:
然后你可以询问 Eloquent 你的物品是否可以装备:
$item = User::with('items')->get()->find(1)->items->find(2)->pivot->equipable;
Keep two things in mind:
请记住两件事:
- Eloquent uses 'items' as a key internally, so that might interfere.
- 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.
- Eloquent 在内部使用“项目”作为键,因此可能会产生干扰。
- 您在“get()”之前放置的任何方法都是数据库查询的一部分。“get()”之后的所有内容都由 PHP 在对象上处理。在大多数情况下,后者会更慢。