为急切加载的表列提供别名

发布于 2025-01-11 13:42:39 字数 374 浏览 2 评论 0原文

我知道我可以从急切加载的表中选择特定列,但我可以给它们一个别名吗?例如:

Post::select('name as name1')
    ->with(['users' => function ($query) {
        $query->select('id', 'name as name2');
    }])
    ->get()

或者

Post::select('name as name1')
   ->with('users:id,name as name2');

我想给它自定义别名,而不仅仅是在前面添加表名称。但无论哪种方式,我都不知道该怎么做

I know I can select specific columns from eager loaded tables, but can I give them an alias? So for example:

Post::select('name as name1')
    ->with(['users' => function ($query) {
        $query->select('id', 'name as name2');
    }])
    ->get()

or

Post::select('name as name1')
   ->with('users:id,name as name2');

I would like to give it custom alias, not just to prepend table name. But either way, I do not know how to do it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

桃扇骨 2025-01-18 13:42:39

是的,您可以向预先加载的列添加别名。您现在所做的似乎是正确的,但您还应该选择与您的 Post 类有关系的列。举个例子:

Post::select('name as name1')
    ->with(['users' => function ($query) {
        $query->select('id', 'post_id', 'name as name2');
    }])
    ->get()

当然,不要忘记在 Post 类中添加 hasMany 关系。例如:

// app/Models/Post.php

...

class Post extends Model
{
    ...

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

Yes, you can add aliases to the eagerly loaded column. What you're doing now seems correct, but you should also select the column that has a relationship with your Post class. As an example:

Post::select('name as name1')
    ->with(['users' => function ($query) {
        $query->select('id', 'post_id', 'name as name2');
    }])
    ->get()

And of course, don't forget to add hasMany relationship in your Post class. For example:

// app/Models/Post.php

...

class Post extends Model
{
    ...

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文