【问题标题】:Laravel Pluck from 'with relation'Laravel Pluck 来自“与关系”
【发布时间】:2020-05-28 03:58:43
【问题描述】:

需要从与关系中提取。我在下面分享代码。

我的控制器:

$type = StandType::with(['brieftype' => function($q) use ($brief_id){
        $q->where('brief_id', $brief_id);
      }])->get()->keyBy('name');

我的模特:

 public function brieftype(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany('App\Models\BriefType', 'key', 'name');
    }

我想这样回应:

[Blabla] => {
  'title' => 'my title',
  'name' => 'my name'
  'brieftype' => ['name1', 'name2', 'name3', 'name4']
}

【问题讨论】:

    标签: laravel relationship pluck


    【解决方案1】:

    试试这个。

    $types = $types->map(function ($type) {
        $type->brieftype = $type->brieftype->pluck('name')->toArray();
        return $type;
    })->toArray();
    

    【讨论】:

      【解决方案2】:

      这样做。它将返回一个带有brieftype 的集合

      $types = $types->map(function ($type) {
                      $type->brieftype = $type->brieftype->pluck('name');
                      return $type;
                  });
      
      dd($types);
      

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        • 2014-01-03
        • 2014-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多