从 Laravel 的belongsToMany 关系中选择自定义列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23709936/
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
Select custom columns from Laravel belongsToMany relation
提问by Greegus
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.
我试图只选择多对多关系上的特定属性users
,就像一对一一样。但是使用select()
onbelongsToMany()
似乎被忽略了,我仍然获得所有用户属性。
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();
Is there a way of filtering only specified columns from related entity with belongsToMany()
?
有没有办法只过滤来自相关实体的指定列belongsToMany()
?
采纳答案by Mark
Yes, you actually can.
是的,你实际上可以。
Computer::with("users")->get(array('column_name1','column_name2',...));
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 :
但是,如果数据透视表链接的两个表的列名相同,请小心。在这种情况下,您需要以点表示法指定表名,tableName.columnName
。例如,如果用户和计算机都有列名id
,则需要执行以下操作:
Computer::with("users")->get(array('users.id','column_name2',...));
回答by Antoine Augusti
According to Taylor Otwell it is not currently possible: https://github.com/laravel/laravel/issues/2679
根据 Taylor Otwell 的说法,目前不可能:https: //github.com/laravel/laravel/issues/2679
I have tried to use a lists('user.email')
at the end of the query but I can't make it work.
我试图lists('user.email')
在查询结束时使用 a但我无法让它工作。
回答by Abdenacer Rachedi
Computer::with(["users" => function($query){
$query->select('column1','column2','...');
}])->get();