問題描述
我有一個名為 Eloquent 的 eloquent 模型:
I have an eloquent model named Eloquent:
Products::where("actice", "=", true)->get()->toArray();
現(xiàn)在我想給它添加join語句,我已經(jīng)定義了一個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
所以在最終結(jié)果數(shù)組中我這樣做:
So that in the final result array I do :
$result[$i]['tag_name'];
雖然現(xiàn)在我必須:
$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();
這篇關(guān)于如何在 Eloquent 中為列的名稱設(shè)置別名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!