0

需要从关系中汲取灵感。我在下面分享代码。

我的控制器:

$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']
}
4

2 回答 2

1

试试这个。

$types = $types->map(function ($type) {
    $type->brieftype = $type->brieftype->pluck('name')->toArray();
    return $type;
})->toArray();
于 2020-05-28T04:23:21.373 回答
1

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

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

dd($types);
于 2020-05-28T07:51:28.173 回答