laravel - Eloquent 具有超过 2 个参数的 Pluck 函数

标签 laravel eloquent

大家好,我尝试在 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/

相关文章:

php - 使用 Eloquent 从带有外键的单个表中获取数据到另外两个表 - laravel

laravel-5 - Laravel 5.7 直接从数据库填充数据以选择输入

php - 如何使用 Laravel 将德语翻译成英语(本地化?)

reactjs - CloudFlare JS挑战打破了我的SPA

php - 我在迁移表时遇到问题。这个问题如下

php - Laravel - 在 whereHas Closure 内动态访问模型属性

database - 路由 [/update-user/9] 未定义。 (查看: C:\xampp\htdocs\Investipediaa\resources\views\frontend\layouts\settings. blade.php)

apache - 在 ubuntu 上部署 Laravel

Laravel-echo-server docker 化问题

php - undefined variable 。拉维