从Laravel选择自定义列属于多个关系 [英] Select custom columns from Laravel belongsToMany relation

查看:190
本文介绍了从Laravel选择自定义列属于多个关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在多对多关系用户中仅选择特定属性,就像一对一一样。但是,在$ code> belongsToMany()中使用 select()似乎被忽略,我仍然收到所有的User属性。

Im trying to select only specific attributes on the many-to-many relation users, just like in one-to-one. But using select() on belongsToMany() seem to be ignored and i'm still getting all the User attributes.

class Computer extends Eloquent {
    public function users() {
        return $this->belongsToMany("User")->select("email");
    }

    public function admin() {
        return $this->hasOne("User")->select("email");
    }
}

Computer::with("users")->get();

有没有办法只使用 belongsToMany )

推荐答案

是的,你

Yes, you actually can.

Computer::with("users")->get(array('column_name1','column_name2',...));

请注意,如果您的数据透视表链接的两个表都具有相同的列名称。在这种情况下,您需要以点表示法, tableName.columnName 指定表名。例如,如果用户和计算机都有列名称 id ,则需要执行以下操作:

Be careful though if you have the same column name for both tables linked by your pivot table. In this case, you need to specify the table name in dot notation, tableName.columnName. For example if both users and computer has a column name id, you need to do :

Computer::with("users")->get(array('users.id','column_name2',...));

这篇关于从Laravel选择自定义列属于多个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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