使用“with()”获得特定的列功能在Laravel雄辩 [英] Get specific columns using "with()" function in Laravel Eloquent
问题描述
我有两个表用户
和发布
一个用户
有很多帖子
和一个帖子
仅属于一个用户
。
在我的用户
模型中我有 hasMany
public function post(){
return $ this-> hasmany('post');
}
在我的帖子中
模型我有 belongsTo
关系,如
public function user(){
return $ this-> belongsTo('user');
}
现在我想使用口述来加入这两个表with()
,但希望从第二个表格中得到特定的列。我知道我可以使用查询构建器
,但是我不会使用它。
当在发布
模型时,我写
public function getAllPosts (){
return Post :: with('user') - > get();
}
它运行以下排队
$($< 2>)中的` $ b
但是我想要
select * from`posts`
select id,username from`users` where`users`.`id` in(< 1>,< 2>)
当我使用
发布: :与( '用户') - >得到(阵列( '列' ....));
它只从第一个表返回列。我想使用与第二个表中的()
的特定列。我该怎么做?
我找到了解决方案。可以通过在中将
函数传递给()
作为数组的第二个索引
Post :: with(array('user'=> function($ query){
$ query-> select 'id','username');
})) - > get();
它只会选择 id
和 username
从其他表。我希望这将有助于他人。
请记住,主键(在这种情况下为id) $ query-> select()来实际检索必要的结果。
I have two tables User
and Post
One User
have many posts
and one post
belongs to only one user
.
In my User
Model I have hasMany
relation like
public function post(){
return $this->hasmany('post');
}
And in my post
model I have belongsTo
relation like
public function user(){
return $this->belongsTo('user');
}
Now I want join of these two tables using Eloquent with()
but want specific columns from second table. I know I can use query Builder
but I don't wat to use that.
When In post
model I write
public function getAllPosts() {
return Post::with('user')->get();
}
It runs following queires
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
But I want
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
When I use
Post::with('user')->get(array('columns'....));
It only returns column from first table. I want specific columns using with()
from second table. How can I do that?
Well I found the solution. It can be done one by passing a closure
function in with()
as second index of array like
Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
It will only select id
and username
from other table. I hope this will help others.
Remember that the primary key (id in this case) is necessary in the $query->select() to actually retrieve the necessary results.
这篇关于使用“with()”获得特定的列功能在Laravel雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!