我有两个表,User和Post。一个用户可以有多个帖子,一个帖子只能属于一个用户。

在我的用户模型中,我有一个hasMany关系…

public function post(){
    return $this->hasmany('post');
}

在我的post模型中,我有一个belongsTo关系…

public function user(){
    return $this->belongsTo('user');
}

现在我想使用Eloquent with()连接这两个表,但想要第二个表中的特定列。我知道我可以使用查询生成器,但我不想这样做。

在Post模型中,我写…

public function getAllPosts() {
    return Post::with('user')->get();
}

它运行以下查询…

select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)

但我想要的是…

select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)

当我用…

Post::with('user')->get(array('columns'....));

它只返回第一个表中的列。我想要第二个表中使用with()的特定列。我该怎么做呢?


当前回答

在Post模型中:

public function userWithName()
{
    return $this->belongsTo('User')->select(array('id', 'first_name', 'last_name'));
}

现在你可以使用$post->userWithName

其他回答

EmployeeGatePassStatus::with('user:id,name')->get();

在我的用户模型中使用belongsToMany关系时,我也遇到了同样的问题。

经过长时间的搜索和试验和测试方法。我找到了这个答案

您必须确保从关系的任何一方选择了关系所需的id和任何外键。这使得Eloquent能够匹配父母和孩子。

原创版权归https://stackoverflow.com/a/64233242/1551102所有

所以我包括了

Groups::select('groupid')
...

而且效果很好。尽管现在我想知道如何在取回后隐藏groupid字段。 我知道我可以简单地遍历数组并删除它。但是还有其他方法吗?可能是一个更简单更好的方法。

当走另一条路(hasMany):

User::with(['post'=>function($query){
    $query->select('id','user_id');
}])->get();

不要忘记包含外键(假设在本例中为user_id)来解析关系,否则关系将得到零结果。

有条件的尝试。

$id = 1;
Post::with(array('user'=>function($query) use ($id){
    $query->where('id','=',$id);
    $query->select('id','username');
}))->get();

注意,如果你只需要表中的一列,那么使用'lists'是非常好的。在我的情况下,我正在检索用户最喜欢的文章,但我只想要文章id的:

$favourites = $user->favourites->lists('id');

返回一个id数组,例如:

Array
(
    [0] => 3
    [1] => 7
    [2] => 8
)