Laravel 使用 concat with pluck 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40132046/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:38:19  来源:igfitidea点击:

Laravel use of concat with pluck method

laravelconcatlaravel-5.3pluck

提问by Punit Gajjar

I am using Laravel.5.3 and below is my query

我正在使用 Laravel.5.3,以下是我的查询

$ProjectManagers = Employees::where("designation" , 1)
->pluck(DB::raw('CONCAT(first_name," ",last_name) AS name'),'id');

which throws an error that

这引发了一个错误

Illegal offset type in isset or empty

isset 或 empty 中的非法偏移类型

May i know if this is the correct method ?

我可以知道这是否是正确的方法吗?

if i dont use contact and use like

如果我不使用联系人并使用类似

$ProjectManagers = Employees::where("designation" , 1)->pluck('first_name','id');

which is working correct and giving me result

这是工作正确并给我结果

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [8] => Punit
        )

)

Expected Result :

预期结果 :

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [8] => Punit Gajjar
        )

)

where first name and last name are concatenated.

其中名字和姓氏连接在一起。

回答by martincarlin87

Try changing the eloquent query to:

尝试将 eloquent 查询更改为:

$ProjectManagers = Employees::select(
            DB::raw("CONCAT(first_name,' ',last_name) AS name"),'id')
            ->where('designation', 1)
            ->pluck('name', 'id');

回答by Bla? Ora?em

The most elegant solution is to create an accessor.

最优雅的解决方案是创建一个访问器

Open your Employeesclass (model) and add an accessor function:

打开你的员工类(模型)并添加一个访问器函数:

public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

After that, just simply use:

之后,只需简单地使用:

$ProjectManagers = Employees::where('designation', 1)->get()->pluck('full_name', 'id');

回答by Hasib Kamal

I also faced a problem like that with join query here is the solution of my problem

我也遇到过这样的问题,连接查询这里是我的问题的解决方案

$studentDegree = Student::leftJoin('degree','degree.student_id','=','student.id')
->select(
      DB::raw("CONCAT(student.name,'-',degree.name) AS name_degree"),
      'student.id'
)->lists('name_degree','id');