如何在 Eloquent 中为列的名称设置别名
我有一个名为 Eloquent 的 eloquent 模型:
I have an eloquent model named Eloquent:
Products::where("actice", "=", true)->get()->toArray();
现在我想给它添加join语句,我已经定义了一个scopeQuery:
Now I want to add join-statement to it, I have defined a scopeQuery with:
public function scopeJoinWithTags($query)
{
return $query->leftJoin("tags", "tags.id", "=", "products.tag_id");
}
然后我们的主要查询更改为:
Then our main query changes to:
Products::where("actice", "=", true)->joinWithTags->get()->toArray();
我得到的没问题,这正是我所期望的,但我想将标签表的名称属性更改为 tag_name,我该怎么做?我的意思是,我在查询中的某处说:
What I get is OK, it is what I do expect, but I want to change the name property of tags table to tag_name, how should I do that? I mean, i say somewhere in my query to:
tags.name AS tag_name
所以在最终结果数组中我这样做:
So that in the final result array I do :
$result[$i]['tag_name'];
虽然现在我必须:
$result[$i]['name'];
推荐答案
最简单的方法是将您需要的字段添加到 get()
方法中,并为您想要的字段添加别名在那里重命名.
Simplest way to do this would be to add the fields you need to the get()
method and alias the ones you want to rename there.
Products::where("actice", "=", true)
->joinWithTags
->get(['tags.name AS tag_name', 'products.*'])
->toArray();
相关文章