从 Laravel 的belongsToMany 关系中选择自定义列 [英] Select custom columns from Laravel belongsToMany relation

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

问题描述

我试图只选择多对多关系 users 上的特定属性,就像一对一一样.但是在 belongsToMany() 上使用 select() 似乎被忽略了,我仍然得到所有用户属性.

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() 仅从相关实体中过滤指定的列?

Is there a way of filtering only specified columns from related entity with belongsToMany()?

推荐答案

是的,你实际上可以.

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 的belongsToMany 关系中选择自定义列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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