【问题标题】:Pluck the values from WITH Eloquent in Laravel从 Laravel 中的 WITH Eloquent 中提取值
【发布时间】:2020-11-19 04:02:20
【问题描述】:

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

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 列。 我怎样才能做到这一点?

非常感谢您!

【问题讨论】:

  • 这能回答你的问题吗? Laravel pluck fields from relations
  • pluck('profile.first_name');
  • 我认为你需要 only 而不是 pluck
  • 感谢@miken32!另外我想知道是否可以在采摘内添加姓氏?因为我需要在选择字段中显示的是名字和姓氏
  • pluck() 用于从结果中提取一列。您可能正在寻找get(),或者上面建议的only()

标签: laravel pluck


【解决方案1】:

你做其中之一

$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(),它将集合转换为数组.

【讨论】:

  • 您好,您知道如何使用 profile.first_name 和 profile.lastn_ame 作为选择字段中的选择,而不是用户表中的“名称”吗?
  • 你可以像profile.first_nameprofile.last_name一样访问它
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2017-04-01
  • 2013-05-27
  • 2020-07-09
  • 1970-01-01
  • 2021-09-08
  • 2014-07-30
  • 1970-01-01
相关资源
最近更新 更多