[英]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');
這引發了一個錯誤
isset 或 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
)
)
其中名字和姓氏連接在一起。
最優雅的解決方案是創建一個訪問器。
打開你的員工類(模型)並添加一個訪問器函數:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
之后,只需簡單地使用:
$ProjectManagers = Employees::where('designation', 1)->get()->pluck('full_name', 'id');
嘗試將 eloquent 查詢更改為:
$ProjectManagers = Employees::select(
DB::raw("CONCAT(first_name,' ',last_name) AS name"),'id')
->where('designation', 1)
->pluck('name', '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();
我也遇到過這樣的問題,連接查詢這里是我的問題的解決方案
$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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.