我有两张桌子, User
和 Post
。一个 User
可以有很多 posts
和一个 post
只属于一个 user
。
在我的 User
模型中,我有一个 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()
的特定列。我怎样才能做到这一点?
原文由 Awais Qarni 发布,翻译遵循 CC BY-SA 4.0 许可协议
好吧,我找到了解决方案。可以通过在
with()
中传递closure
函数作为数组的第二个索引来完成它只会从其他表中选择
id
和username
。我希望这对其他人有帮助。请记住, 主键(在本例中为 id)需要是
$query->select()
中的第一个参数才能实际检索必要的结果。*