如何将列与Laravel 4 Eloquent连接起来?

2022-08-30 11:41:12

我有一个名为包含tenantdetails

Tenant_Id | First_Name | Last_Name | ........

我想通过MySQL的串联函数检索并作为一列。所以我写在我的下面First_NameLast Namecontroller

$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模型以更优雅的方式实现这一点,如下所示:

在我们的 :model

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

答案 1
Tenant::select('Tenant_Id', DB::raw('CONCAT(First_Name, " ", Last_Name) AS full_name'))
    ->orderBy('First_Name')
    ->lists('full_name', 'Tenant_Id');

答案 2

一个简单的方法是使用 。它由Tailor在selectRawJan 30, 2014

Tenant::selectRaw('CONCAT(First_Name, " ", Last_Name) as TenantFullName, id')->orderBy('First_Name')->lists('TenantFullName', 'id'))

推荐