大家好,我尝试在 Eloquent 上使用 pluck 函数查询显示超过 2 个参数。
这是我的查询:
$licence_entraineur = Licencies::where(['structure_id' => Auth::user()->structure->id])->where('type_licence_id' , '1')->pluck('lb_nom' , 'num_licence' , 'id');
我刚刚得到'lb_nom'
,我也想要'num_licence'
,有人知道该怎么做吗?
最佳答案
您可以将数组传递给 get()
方法:
$licence_entraineur = Licencies::where(['structure_id' => Auth::user()->structure->id])
->where('type_licence_id', '1')
->get(['lb_nom', 'num_licence', 'id']);
或者使用select()
方法:
$licence_entraineur = Licencies::select('lb_nom', 'num_licence', 'id')
->where(['structure_id' => Auth::user()->structure->id])
->where('type_licence_id', '1')
->get();
如果你想get pluck()
like array without keys ,您可以在集合上使用 map()
方法:
$licence_entraineur->map(function($i) {
return array_values((array)$i);
});
更新
在评论中您说过想要获得混合结果,因此请使用以下代码(适用于 5.4,不适用于 5.3):
$licence_entraineur = Licencies::select('lb_nom', 'num_licence', 'lb_prenom', 'id')
->where(['structure_id' => Auth::user()->structure->id])
->where('type_licence_id' , '1')
->get()
->mapWithKeys(function($i) {
return [$i->id => $i->lb_nom.' - '.$i->num_licence.' - '.$i->lb_prenom];
});
此外,您可以使用 an accessor这里。像这样的东西:
public function getTitleAttribute($value)
{
return $this->lb_nom.' - '.$this->num_licence.' - '.$this->lb_prenom;
}
并将其用作->pluck('title', 'id')
关于laravel - Eloquent 具有超过 2 个参数的 Pluck 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996812/