php 如何在 Eloquent 中为列的名称设置别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26958080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:06:48  来源:igfitidea点击:

How to alias the name of a column in Eloquent

phplaraveleloquent

提问by Mostafa Talebi

I have an eloquent model named Eloquent:

我有一个名为 Eloquent 的 eloquent 模型:

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

Now I want to add join-statement to it, I have defined a scopeQuery with:

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

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();

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:

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

 tags.name AS tag_name

So that in the final result array I do :

所以在最终结果数组中我这样做:

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

While now I have to :

虽然现在我必须:

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

回答by turntwo

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.

最简单的方法是将您需要的字段添加到get()方法中,并为您要重命名的字段添加别名。

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

回答by Disturb

On Laravel 5.4 (I don't know if earlier version also apply) you can do that with the selectmethod:

在 Laravel 5.4(我不知道早期版本是否也适用)上,您可以使用以下select方法执行此操作:

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

At least for me this is cleaner.

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

回答by Adnan Mumtaz

There is also a cleaner way to achieve this

还有一种更清洁的方法来实现这一目标

You can take advantage of laravel mutators

你可以利用 Laravel 的修改器

public function getTagNameAttribute()
{
    return $this->attributes['name'];
}

Hope this helps

希望这可以帮助