I am trying to build a possibility of nested items for my user model.
Actually, every user can have many items, which can have children of their own type (item).
This is the user's relation to item:
/**
* @return \Illuminate\Database\Eloquent\Relations\belongsToMany
*/
public function items()
{
return $this->belongsToMany(Item::class)->withPivot( 'value'');
}
This is how the children are being resolved:
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany(Item::class, 'parent_id');
}
Now - thanks to your help before - I can query the items with children:
$user->items()->whereNull('parent_id')->with('children')->get();
This is the result:
Illuminate\Database\Eloquent\Collection {#3247 all: [ App\Item {#3232 id: 2, parent_id: null, title: "Parent 1", pivot: Illuminate\Database\Eloquent\Relations\Pivot {#3235 user_id: 12, user_item_id: 2, value: "3", }, children: Illuminate\Database\Eloquent\Collection {#3267 all: [ App\Item {#3270 id: 3, parent_id: 2, title: "Child 1", created_at: "2019-10-04 14:29:59", updated_at: "2019-10-04 14:29:59", }, App\Item {#3272 id: 4, parent_id: 2, title: "Child 2", created_at: "2019-10-04 14:30:16", updated_at: "2019-10-04 14:30:16", }, ], }, }, App\Item {#3255 id: 5, parent_id: null, title: "Parent 2", created_at: "2019-10-04 14:36:50", updated_at: "2019-10-04 14:36:50", pivot: Illuminate\Database\Eloquent\Relations\Pivot {#3240 user_id: 12, user_item_id: 5, value: "50", }, children: Illuminate\Database\Eloquent\Collection {#3266 all: [], }, }, ], }
As you can see, the parent items got an pivot value - the children do not have any pivot data. How can I solve that? I learned, that hasMany does not provide pivot.
My question
How can I add pivot data to nested children in this scenario?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire