Laravel concat with pluck 方法的使用

Laravel use of concat with pluck method

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

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

抛出

的错误

Illegal offset type in isset or empty

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

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

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

哪个工作正常并给我结果

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

)

预期结果:

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

)

名字和姓氏连接在一起。

尝试将 eloquent 查询更改为:

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

最优雅的解决方案是创建一个 accessor

打开您的 Employees class(模型)并添加访问函数:

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

之后,只需简单地使用:

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

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

$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');

如果您的列可以为空,那么您应该试试这个

通过 COALESCE

NULL 值转换为空字符串
$ProjectManagers = Employees::select(
            DB::raw("CONCAT(COALESCE(`first_name`,''),' ',COALESCE(`last_name`,'')) AS name"),'id')
            ->where('designation', 1)
            ->pluck('name', 'id')
            ->toArray();