我有两个表,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()
的特定列。我该怎么做?
最佳答案
好吧,我找到了解决方案。它可以通过在 with()
中传递一个 closure
函数作为数组的第二个索引来完成,例如
Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()
它只会从其他表中选择 id
和 username
。我希望这对其他人有帮助。
请记住,主键(在本例中为 id)需要是第一个参数
$query->select()
来实际检索必要的结果。*
关于php - 在 Laravel Eloquent 中使用 “With()” 函数获取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19852927/