从两个表中选择雄辩的列选择

发布于 01-21 05:10 字数 1008 浏览 3 评论 0原文

我有两个桌子,用户和帖子。一个用户可以有很多帖子,一个帖子仅属于一个用户。

在我的用户模型中,我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨与橙与城2025-01-28 05:10:46

只需将代码更改为

public function getAllPosts() {
    return Post::with('users:id,username')->get('id', 'text AS post_text');
}

Just change the code to

public function getAllPosts() {
    return Post::with('users:id,username')->get('id', 'text AS post_text');
}
山田美奈子2025-01-28 05:10:46

下一行中有一个问题:

Post::select('id', 'text AS post_text')->with('user:id, username')->get();

在选择中,它期望一个数组

Post::select(['id', 'text AS post_text'])->with('user.id, username')->get();

There is a problem in the next line:

Post::select('id', 'text AS post_text')->with('user:id, username')->get();

In the select it expects an array

Post::select(['id', 'text AS post_text'])->with('user.id, username')->get();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文