带有Laravel 5雄辩的CONCAT列

吉隆坡Eli​​yaz

认为我是Laravel初学者

目标是:我有两个列,现在我需要在表中id添加component name同一行的前缀

例如(工作)...我有Mysql

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

和输出是

ID

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

我需要用laravel雄辩的方式来表示,因为这里Component是Model name。所以我尝试了类似的东西

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

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

注意:我进行了上述查询,将其称为Internet上可用的查询。

User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))
查尔拉卡

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

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

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

另外,为了使其列表更好,我建议您将查询修改为:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章