How to concatenate columns with Laravel 4 Eloquent?
我有一个名为 tenantdetails 的表,其中包含
1
|
Tenant_Id | First_Name | Last_Name | ……..
|
我想通过 MySQL 的连接函数将 First_Name 和 Last Name 作为一列检索。所以我在我的 controller 中写如下
1
|
$tenants = Tenant::orderBy(‘First_Name’)->lists(‘CONCAT(`First_Name`,””,`Last_Name`)’,‘Tenant_Id’);
|
但结果如下错误:
1
2
3
4
5
6
7 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:
1
2 3 4 |
public function getTenantFullNameAttribute()
{ return $this->attributes[‘First_Name’] .‘ ‘. $this->attributes[‘Last_Name’]; } |
和我们的 controller:
1
2 |
$tenants = Tenant::orderBy(‘First_Name’)->get();
$tenants = $tenants->lists(‘TenantFullName’, ‘Tenant_Id’); |
- 这个模型解决方案很棒。这是在任何地方的文档中吗?
- @Kyle Ridolfo。谢谢。实际上我忘记了解决方案的来源。但我确信直到我搜索解决方案的那一天才出现在文档中。
- 如果有人仍然感兴趣,文档在这里:laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutator??s (这指向最新的 Laravel 版本,您需要查看使用的版本你的项目)。
1
2 3 |
Tenant::select(‘Tenant_Id’, DB::raw(‘CONCAT(First_Name,””, Last_Name) AS full_name’))
->orderBy(‘First_Name’) ->lists(‘full_name’, ‘Tenant_Id’); |
- 有没有可能只用雄辩的 orm 做到这一点
- 我是laravel的初学者。我认为它是 Fluent Query Builder 和 Eloquent 的结合。我错了吗?
- 这是雄辩。在 Eloquent 中,您可以使用 Fluent 中的所有内容。但无论如何,它仍然是雄辩的。为什么这对你来说还不够?
- 谢谢,这对我来说已经足够了。我只是想知道我们是否只能通过雄辩来做到这一点(因为现在我正在学习过程中)。谢谢您的帮助..
- 在 Laravel 5 中,您必须使用 use DB; 或使用反斜杠调用它:\\DB::raw…
- @manuthalasseril 我使用了@michel-ayres 建议的 selectRaw 方法,但将其放在查询范围(laravel.com/docs/4.2/eloquent#query-scopes)中以进行简单的重用……让它看起来更多”雄辩”:)
一个简单的方法是使用selectRaw。它是由 Tailor 在 Jan 30, 2014
中实现的
来源
1
|
Tenant::selectRaw(‘CONCAT(First_Name,””, Last_Name) as TenantFullName, id’)->orderBy(‘First_Name’)->lists(‘TenantFullName’, ‘id’))
|
lists() 方法用于从选定结果中选择列。所以首先联系名字和姓氏,并在选择语句
中为该列提供新的别名
1
|
$tenants = Tenant::orderBy(‘First_Name’)->select(DB::row(‘CONCAT(`First_Name`,””,`Last_Name`) as name’),‘Tenant_Id’)->lists(‘name’, ‘id’);
|
那么你可以在lists()方法中选择这个别名
- 只是关于拼写错误 DB::row 应该是 DB::raw 的注释,您可能需要编辑您的答案。
你应该使用 DB::raw() 来连接那些字段
1
2 3 4 5 6 7 |
Tenant::select(
‘Tenant_Id’, DB::raw(‘CONCAT(First_Name,”-“,Last_Name) as full_name’) ) |
您也可以使用查询生成器来执行此操作
喜欢:
1
2 3 |
DB::table(‘Tenant’)
->selectRaw(‘CONCAT(First_Name,” -“, Last_Name) as fullName, id’) ->get(); |
希望对您有所帮助:)
来源:https://www.codenong.com/22008487/