如何在 Eloquent 中为列名起别名

2022-08-30 11:47:54

我有一个雄辩的模型,名叫Eloquent:

Products::where("actice", "=", true)->get()->toArray();

现在我想向它添加连接语句,我已经定义了一个 scopeQuery:

public function scopeJoinWithTags($query)
    {
        return $query->leftJoin("tags", "tags.id", "=", "products.tag_id");
    }

然后,我们的主查询将更改为:

Products::where("actice", "=", true)->joinWithTags->get()->toArray();

我得到的是好的,这是我所期望的,但是我想将标签表的名称属性更改为tag_name,我该怎么做?我的意思是,我在查询中的某个地方说:

 tags.name AS tag_name

因此,在最终结果数组中,我这样做:

$result[$i]['tag_name'];

而现在我必须:

$result[$i]['name'];

答案 1

执行此操作的最简单方法是将所需的字段添加到方法中,并别名要在其中重命名的字段。get()

Products::where("actice", "=", true)
    ->joinWithTags
    ->get(['tags.name AS tag_name', 'products.*'])
    ->toArray();

答案 2

在Laravel 5.4上(我不知道早期版本是否也适用),你可以用这个方法做到这一点:select

Products::where("actice", "=", true)
    ->joinWithTags
    ->select('tags.name AS tag_name', 'products.*')
    ->get();

至少对我来说,这更干净。


推荐