Laravel 4雄辩的枢纽工作台 [英] Laravel 4 eloquent pivot table

查看:96
本文介绍了Laravel 4雄辩的枢纽工作台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表:用户,项目和user_items。一个用户有很多项目,一个项目属于许多用户。



表:

 code>用户
id
用户名
密码

项目
id
名称
可配置

User_items
id
user_id
item_id
装备

模型:

 类用户扩展Eloquent {
public function items()
{
return $ this-> belongsToMany('Item','user_items')
- > withPivot('equip');
}
}

类项目扩展Eloquent {
public function users()
{
return $ this-> belongsToMany(' User','user_items');
}
}

在pivot(user_items)表中,我有一个非常重要的名为装备的列。



我有一个表单,用户可以装备,取消装备和抛出物品。此表单具有一个带有pivot(user_items)表行ID的隐藏字段。因此,当用户尝试装备物品时,系统会检查该物品是否配备。



所以,我想要一个包含枢轴数据和物料数据的对象,基于来自数据透视表的item_id,我可以发送给处理程序(所有逻辑都处理)。



所以我要做的是首先访问数据透视表,然后访问项目表。



这样的东西(不行):

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

这可能吗?

解决方案

您首先必须在您的枢轴拨号上包含可配置:

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

那么你可以询问你的项目是否可配备:

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

记住两件事:


  1. Enloquent在内部使用'items'作为一个关键字,这样可能会干扰。

  2. 无论在get()之前放置什么方法都是数据库查询的一部分。 get()之后的所有内容都由PHP在对象上处理。在大多数情况下,后者会更慢。


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?

解决方案

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.

这篇关于Laravel 4雄辩的枢纽工作台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆