php CONCAT 列与 Laravel 5 eloquent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42735071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CONCAT columns with Laravel 5 eloquent
提问by Eliyaz KL
Consider me as laravel beginner
把我当作 Laravel 初学者
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.
目标是:我有两个列,现在我需要id
以component name
表中的同一行作为前缀。
For Example (Working)... I have Mysql like
例如(工作)......我有Mysql
SELECT CONCAT(components.name," ", components.id) AS ID
FROM `components`
And output is
输出是
ID
ID
|TestComp 40 |
-------------
|component 41 |
-------------
|test 42 |
I need the same in laravel eloquent way, as here Component is Model name. So i tried something like
我需要同样的 Laravel 雄辩方式,因为这里的组件是模型名称。所以我尝试了类似的东西
$comp=Component::select("CONCAT('name','id') AS ID")->get()
but it doesn't work.
I think because the syntax is wrong.
Kindly help me with the correct syntax. Using laravel
Models
.
但它不起作用。
我认为是因为语法错误。
请帮助我使用正确的语法。使用laravel
Models
.
Note: I made the above query, referring this as which available on internet.
注意:我进行了上述查询,将其称为 Internet 上可用的查询。
User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))
回答by Tschallacka
You need to wrap your query in DB::raw
:
您需要将查询包装在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.
另外,请注意,因为您正在执行这样的查询,所以您的模型的行为可能会有所不同,因为此 select 会从 select 语句中删除所有其他字段。因此,如果没有新查询,您将无法从模型中读取其他字段。所以只用它来读取数据而不是修改数据。
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.
回答by Bmoeller
I came to this post for answers myself. The only problem for me is that the answer didn't really work for my situation. I have numerous table relationships setup and I needed one of the child objects to have a concatenated field. The DB::raw
solution was too messy for me. I kept searching and found the answer I needed and feel it's an easier solution.
我自己来到这个帖子寻求答案。对我来说唯一的问题是答案并不适合我的情况。我有很多表关系设置,我需要其中一个子对象来连接字段。该DB::raw
解决方案对我来说太乱了。我不断搜索并找到了我需要的答案,并觉得这是一个更简单的解决方案。
Instead of DB::raw
, I would suggest trying an Eloquent Accessor. Accessors allow you to retrieve model attributes AND to create new ones that are not created by the original model.
相反DB::raw
,我建议尝试使用Eloquent Accessor。访问器允许您检索模型属性并创建不是由原始模型创建的新属性。
For instance, let's say I have a basic USER_PROFILE table. It contains id, first_name, last_name
. I have the need to CONCAT the two name attributes to return their user's full name. In the USER_PROFILE Model I created php artisan make:model UserProfile
, I would place the following:
例如,假设我有一个基本的 USER_PROFILE 表。它包含id, first_name, last_name
. 我需要连接这两个名称属性以返回其用户的全名。在我创建的 USER_PROFILE 模型中php artisan make:model UserProfile
,我将放置以下内容:
class UserProfile extends Model
{
/**
* Get the user's full concatenated name.
* -- Must postfix the word 'Attribute' to the function name
*
* @return string
*/
public function getFullnameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
}
From here, when I make any eloquent calls, I now have access to that additional attribute accessor.
从这里开始,当我进行任何雄辩的调用时,我现在可以访问该附加属性访问器。
| id | first_name | last_name |
-------------------------------
| 1 | John | Doe |
$user = App\UserProfile::first();
$user->first_name; /** John **/
$user->fullname; /** John Doe **/
I will say that I did run into one issue though. That was trying to create a modified attribute with the same name, like in your example (id, ID). I can modify the id value itself, but because I declared the same name, it appears to only allow access to that field value and no other field.
我会说我确实遇到了一个问题。那是试图创建一个具有相同名称的修改过的属性,就像在你的例子中一样(id,ID)。我可以修改 id 值本身,但是因为我声明了相同的名称,它似乎只允许访问该字段值而不允许访问其他字段。
Others have said they can do it, but I was unable to solve this questions EXACT problem.
其他人说他们可以做到,但我无法解决这个问题确切的问题。
回答by bravohex
I working on posgresql and mysql:
我在 posgresql 和 mysql 上工作:
DB::raw('CONCAT(member.last_name, \' \', member.first_name) as full_name')
回答by G-Man
Scrubbing the Data: Before using Laravel and now, when developing in other languages, I would use CONCAT() on a regular basis. The answers here work to a degree but there still isn't an elegant way to use CONCAT() in Laravel/Eloquent/Query Builder that I have found.
清理数据:在使用 Laravel 之前,现在,在使用其他语言进行开发时,我会定期使用 CONCAT()。这里的答案在一定程度上有效,但仍然没有一种优雅的方式在我发现的 Laravel/Eloquent/Query Builder 中使用 CONCAT()。
However, I have found that concatenating the cols AFTER returning the results works well for me and is usually very fast - Scrubbing the data - ( unless you have a huge result which should probably be "chunked" anyway for performance purposes ).
但是,我发现在返回结果后连接 cols 对我来说效果很好,并且通常非常快 - 清理数据 - (除非你有一个巨大的结果,无论如何为了性能目的应该“分块”)。
foreach($resultsArray AS $row){
$row['fullname'] = trim($row['firstname']).' '.trim($row['lastname']);
}
This is a tradeoff of course but, personally, I find it to be much more manageable and doesn't limit my use of Eloquent as intended as well as the Query Builder. ( the above is pseudo code - not tested so tweak as needed )
这当然是一种权衡,但就我个人而言,我发现它更易于管理,并且不会限制我按预期使用 Eloquent 以及 Query Builder。(以上是伪代码 - 未经测试,请根据需要进行调整)
There are other workarounds as well that don't mess with Eloquent/Query Builder functionality such as creating a concatenated col in the table, in this case full_name - save the full name when the record is inserted/updated. This is not uncommon.
还有其他解决方法不会干扰 Eloquent/Query Builder 功能,例如在表中创建一个连接的 col,在这种情况下是 full_name - 在插入/更新记录时保存全名。这并不少见。