为急切加载的表列提供别名
我知道我可以从急切加载的表中选择特定列,但我可以给它们一个别名吗?例如:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以向预先加载的列添加别名。您现在所做的似乎是正确的,但您还应该选择与您的
Post
类有关系的列。举个例子:当然,不要忘记在
Post
类中添加hasMany
关系。例如: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:And of course, don't forget to add
hasMany
relationship in yourPost
class. For example: