我有一个名为 tenantdetails
的表,其中包含
Tenant_Id | First_Name | Last_Name | ........
我想通过 MySQL 的连接函数将 First_Name
和 Last Name
检索为一列。所以我在我的 controller
中写如下
$tenants = Tenant::orderBy('First_Name')->lists('CONCAT(`First_Name`," ",`Last_Name`)','Tenant_Id');
但结果如下错误:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`," ",`First_Name`)`, `Id` from `tenantdetails` order by `F' at line 1 (SQL: select `CONCAT(`First_Name`," ",`Last_Name`)`, `Id` from `tenantdetails` order by `First_Name` asc).
在 Laravel Eloquent 中调用 MySQL 的函数时如何避免反引号。我只对 Eloquent 感兴趣(对流利的查询不感兴趣)。提前致谢。
更新
感谢@Andreyco 帮助我。我们可以使用 Laravel 模型以更优雅的方式实现这一点,如下所示:
在我们的模型
中:
public function getTenantFullNameAttribute()
{
return $this->attributes['First_Name'] .' '. $this->attributes['Last_Name'];
}
在我们的 Controller
中:
$tenants = Tenant::orderBy('First_Name')->get();
$tenants = $tenants->lists('TenantFullName', 'Tenant_Id');
最佳答案
Tenant::select('Tenant_Id', DB::raw('CONCAT(First_Name, " ", Last_Name) AS full_name'))
->orderBy('First_Name')
->lists('full_name', 'Tenant_Id');
https://stackoverflow.com/questions/22008487/