在 Laravel 中从 WITH Eloquent 中提取值

问题描述 投票:0回答:1

我有一个下拉框,仅显示具有收集者和借款人角色的用户。这是我的代码

public function create()
{
    $users = User::whereHas('roles', function ($q) {
                $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');
            })
            ->with('profile')
            ->get()
            ->pluck('name','id');

    return view('dashboard.documents.create', compact('users'));
}

这段代码很好,但我要提取的是“个人资料”中的first_name、last_name 和user_id 列。 我怎样才能实现这一目标?

php laravel eloquent with-statement pluck
1个回答
0
投票

您执行其中一项

$users = User::whereHas('roles', function ($q) {
             $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
            ->with('profile')
            ->select('name','id')
            ->get();

或者

$users = User::whereHas('roles', function ($q) {
             $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
            ->with('profile')
            ->get(['name','id']);

这两种方式都会返回一个带有相关模型的

collection
,每个模型记录都会有选定的列,如果你想将其转换为数组,你可以在两种方式后添加
->toArray()
,它将把集合转换为数组。

© www.soinside.com 2019 - 2024. All rights reserved.