如何在 Eloquent 中为列的名称添加别名


How to alias the name of a column in Eloquent

我有一个名为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();

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

 tags.name AS tag_name

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

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

虽然现在我必须:

$result[$i]['name'];
最简单的

方法是将所需的字段添加到get()方法中,并为要在此处重命名的字段添加别名。

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

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

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

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

还有一个更简洁的方法来实现这一点

你可以利用拉拉维尔突变体

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

希望这有帮助

这是我

的首选。适合与旧列名向后兼容。

将以下内容添加到模型中

  1. protected $appends = ['old_column_name'];
  2. public function getOldColumnNameAttribute() {
      return $this->attributes['new_column_name'];
    }
    public function setOldColumnNameAttribute($value) {
      $this->attributes['new_column_name'] = $value;
      return $this;   
    }