我有一张叫做tenantdetails的桌子,里面有

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

and I want to retrieve First_Name and Last Name as one column via the concatenation function of MySQL. So I write in my controller as follows

$tenants = Tenant::orderBy('First_Name')->lists('CONCAT(`First_Name`," ",`Last_Name`)','Tenant_Id');

But results the following error:

 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).

How can we avoid the backticks while calling a function of MySQL in Laravel Eloquent. I am interested only in Eloquent (not in fluent query). Thanks in advance.

Update

Thanks to @Andreyco for helping me. We can achieve this in a more elegant way using Laravel models, as below:

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

推荐答案

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

Laravel相关问答推荐

如何在 Laravel 9 中获取带分页的订单列表?

验证判断请求的值是否存在于另一个表 Laravel 9 中

如何提取每组 groupBy 查询的唯一值?

Laravel where 子句只返回一个数据库条目

使用Laravel Blade Formatter和PHP Intelephense进行 VSCode 格式化

错误try 访问 null 类型值的数组偏移量laravel 5.8.26 Php 7.4.2

Laravel 5.7 判断Electron邮件是否经过验证

Laravel 5.1 如何在Blade 文件上使用 {{ old('') }} 助手进行无线电输入

如何更改 Laravel5 中的视图文件夹?

如何使用 Laravel 模型访问数据库视图?

控制器外部的 Laravel 访问请求对象

如何重定向到laravel上的公共文件夹

Laravel Eloquent - 加入表时防止覆盖值

Laravel 的 toSql() 方法是否会屏蔽 id? (列值被问号替换)

无法打开laravel.log:无法打开流

Grammar::parameterize() 必须是数组类型

Laravel 事件、监听器、作业(job)、队列之间的区别

判断行是否存在,Laravel

Laravel Route 模型与关系绑定

在 Laravel 中判断会话超时