带有Laravel 5雄辩的CONCAT列 [英] CONCAT columns with Laravel 5 eloquent

查看:79
本文介绍了带有Laravel 5雄辩的CONCAT列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将我视为laravel初学者

Consider me as laravel beginner

目标是:我有两个列,现在我需要在表的同一行的id之前加上id.

The goal is: I have two colums, now I need the id to be prefixed with the component name of same row in the table.

例如(正在工作)...我有Mysql之类的

For Example (Working)... I have Mysql like

SELECT CONCAT(components.name," ", components.id) AS ID
FROM   `components` 

输出是

ID

|TestComp 40  |
 -------------
|component 41 |
 -------------
|test 42      |

我需要用laravel雄辩的方式说同样的话,因为在这里Component是Model name.所以我尝试了类似的东西

I need the same in laravel eloquent way, as here Component is Model name. So i tried something like

$comp=Component::select("CONCAT('name','id') AS ID")->get()

但是它不起作用.
我认为是因为语法错误.
请帮助我正确的语法.使用laravel Models.

but it doesn't work.
I think because the syntax is wrong.
Kindly help me with the correct syntax. Using laravel Models.

注意:我进行了上述查询,将其称为互联网上可用的查询.

Note: I made the above query, referring this as which available on internet.

User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))

推荐答案

您需要将查询包装在DB::raw中:

You need to wrap your query in DB::raw:

$comp = Component::select(DB::raw("CONCAT('name','id') AS ID"))->get()

此外,请注意,因为您正在执行这样的查询,所以模型的行为可能会有所不同,因为此选择会从select语句中删除所有其他字段. 因此,如果没有新的查询,就无法从模型中读取其他字段.因此,仅将其用于读取数据而不是修改数据.

Also, note because you are doing your query like this, your model might behave differently, because this select removes all other fields from the select statement. So you can't read the other fields from your model without a new query. So ONLY use this for READING data and not MODIFYING data.

此外,为了使其包含在一个漂亮的列表中,建议您将查询修改为:

Also, to make it in a nice list, I suggest you modify your query to:

$comp = Component::select(DB::raw("CONCAT('name','id') AS display_name"),'id')->get()->pluck('display_name','id');
// dump output to see how it looks.
dd($comp);// array key should be the arrray index, the value the concatted value.

这篇关于带有Laravel 5雄辩的CONCAT列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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