沃梦达 / 编程问答 / php问题 / 正文

CONCAT 列与 Laravel 5 eloquent

CONCAT columns with Laravel 5 eloquent(CONCAT 列与 Laravel 5 eloquent)

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

问题描述

把我当作 Laravel 初学者

Consider me as laravel beginner

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

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` 

输出是

身份证

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

我需要同样的 Laravel eloquent 方式,因为这里的组件是模型名称.所以我尝试了类似

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.

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

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

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

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.

这篇关于CONCAT 列与 Laravel 5 eloquent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:CONCAT 列与 Laravel 5 eloquent

基础教程推荐