在Laravel Eloquent中使用“ With()”函数获取特定列
我有两个表,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()第二个表中的特定列。我怎样才能做到这一点?
回答:
好吧,我找到了解决方案。可以通过将closure函数with()作为数组的第二个索引传递来完成
Post::with(array('user'=>function($query){ $query->select('id','username');
}))->get();
它只会选择id和username从其他表中选择。我希望这会帮助其他人。
请记住, $ query-> select()中 ,才能实际检索必要的结果。*
以上是 在Laravel Eloquent中使用“ With()”函数获取特定列 的全部内容, 来源链接: utcz.com/qa/435351.html

