Laravel 摘自 'with relation'
Laravel Pluck from 'with relation'
需要与关系有联系。我在下面分享代码。
我的控制器:
$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']
}
试试这个。
$types = $types->map(function ($type) {
$type->brieftype = $type->brieftype->pluck('name')->toArray();
return $type;
})->toArray();
这样做。它将 return 一个带有 brieftype
的集合
$types = $types->map(function ($type) {
$type->brieftype = $type->brieftype->pluck('name');
return $type;
});
dd($types);
需要与关系有联系。我在下面分享代码。
我的控制器:
$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']
}
试试这个。
$types = $types->map(function ($type) {
$type->brieftype = $type->brieftype->pluck('name')->toArray();
return $type;
})->toArray();
这样做。它将 return 一个带有 brieftype
的集合$types = $types->map(function ($type) {
$type->brieftype = $type->brieftype->pluck('name');
return $type;
});
dd($types);