我有一个名为 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 中为列的名称设置别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
PHP、MySQL PDOException 的死锁异常代码?Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死锁异常代码?)
PHP PDO MySQL 可滚动游标不起作用PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滚动游标不起作用)
PHP PDO ODBC 连接PHP PDO ODBC connection(PHP PDO ODBC 连接)
使用 PDO::FETCH_CLASS 和魔术方法Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔术方法)
php pdo 只从 mysql 获取一个值;等于变量的值php pdo get only one value from mysql; value that equals to variable(php pdo 只从 mysql 获取一个值;等于变量的值)
MSSQL PDO 找不到驱动程序MSSQL PDO could not find driver(MSSQL PDO 找不到驱动程序)