从两个表中选择雄辩的列选择
我有两个桌子,用户和帖子。一个用户可以有很多帖子,一个帖子仅属于一个用户。
在我的用户模型中,我有一个Hasmany的关系...
public function post(){
return $this->hasmany('post');
}
在我的帖子模型中,我有一个属于关系...
public function user(){
return $this->belongsTo('user');
}
现在我想使用WING()的elo table加入这两个表,但希望从第一和第二个表中使用特定的列。我知道我可以使用查询构建器,但我不想。
在帖子模型中,我写...
public function getAllPosts() {
return Post::with('user')->get();
}
它运行以下查询...
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
但是我想要的是...
select `id`, `text AS post_text` from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
当我使用...时...
Post::select('id', 'text AS post_text')->with('user:id, username')->get();
它返回用户null。
{
"id": "1",
"post_text": "text",
"user": null
}
I have two tables, User and Post. One User can have many posts and one post belongs to only one user.
In my User model I have a hasMany relation...
public function post(){
return $this->hasmany('post');
}
And in my post model I have a belongsTo relation...
public function user(){
return $this->belongsTo('user');
}
Now I want to join these two tables using Eloquent with() but want specific columns from the first and second table. I know I can use the Query Builder but I don't want to.
When in the Post model I write...
public function getAllPosts() {
return Post::with('user')->get();
}
It runs the following queries...
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
But what I want is...
select `id`, `text AS post_text` from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
When I use...
Post::select('id', 'text AS post_text')->with('user:id, username')->get();
It returns user null.
{
"id": "1",
"post_text": "text",
"user": null
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
只需将代码更改为
Just change the code to