【发布时间】:2013-11-20 02:25:36
【问题描述】:
我有两张桌子,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() 的特定列。我该怎么做?
【问题讨论】:
标签: php laravel orm eloquent laravel-query-builder