在 Laravel Eloquent 中使用“With()"函数获取特定列 [英] Get Specific Columns Using “With()” Function in Laravel Eloquent
问题描述
我有两个表,User
和 Post
.一个User
可以拥有多个posts
,一个post
只属于一个user
.
I have two tables, User
and Post
. One User
can have many posts
and one post
belongs to only one user
.
在我的 User
模型中,我有一个 hasMany
关系...
In my User
model I have a hasMany
relation...
public function post(){
return $this->hasmany('post');
}
在我的 post
模型中,我有一个 belongsTo
关系...
And in my post
model I have a belongsTo
relation...
public function user(){
return $this->belongsTo('user');
}
现在我想使用 Eloquent with()
连接这两个表,但想要第二个表中的特定列.我知道我可以使用查询生成器,但我不想.
Now I want to join these two tables using Eloquent with()
but want specific columns from the second table. I know I can use the Query Builder but I don't want to.
当我在 Post
模型中编写...
When in the Post
model I write...
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()
的特定列.我该怎么做?
It only returns the column from the first table. I want specific columns using with()
from the second table. How can I do that?
推荐答案
好吧,我找到了解决方案.它可以通过在 with()
中传递一个 closure
函数作为数组的第二个索引来完成,如
Well I found the solution. It can be done one by passing a closure
function in with()
as second index of array like
Post::query()
->with(array('user' => function($query) {
$query->select('id','username');
}))
->get();
它只会从其他表中选择id
和username
.我希望这会对其他人有所帮助.
It will only select id
and username
from other table. I hope this will help others.
请记住,主键(在本例中为 id)必须是第一个参数$query->select()
以实际检索必要的结果.*
Remember that the primary key (id in this case) needs to be the first param in the
$query->select()
to actually retrieve the necessary results.*
这篇关于在 Laravel Eloquent 中使用“With()"函数获取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!