如何在 Eloquent 中为列的名称设置别名 [英] How to alias the name of a column in Eloquent

查看:26
本文介绍了如何在 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();

这篇关于如何在 Eloquent 中为列的名称设置别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆