如何使用Laravel 4 Eloquent连接列? [英] How to concatenate columns with Laravel 4 Eloquent?

查看:56
本文介绍了如何使用Laravel 4 Eloquent连接列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为tenantdetails的表,其中包含

I have a table called tenantdetails which contains

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

,我想通过MySQL的串联函数将First_NameLast Name检索为一列.因此,我在controller中编写如下

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

但是会导致以下错误:

 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感兴趣(对流利的查询不感兴趣).预先感谢.

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.

更新

感谢@Andreyco帮助我.我们可以使用Laravel模型以更优雅的方式实现这一目标,如下所示:

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

在我们的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 4 Eloquent连接列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆