Parent model is not injected related children #49087
Replies: 3 comments 1 reply
-
If anyone else has this same issue, we resolved it in our API resources by instantiating child resource collections with a custom method that sets the parent relation on each of the children: <?php
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
trait ExtensibleCollectionTrait
{
public static function collectionWith(Collection $collection, array $properties): AnonymousResourceCollection
{
return static::collection($collection->map(function ($item) use ($properties) {
foreach ($properties as $prop => $val) {
$item->{$prop} = $val;
}
return $item;
}));
}
} We added that trait to our child resource, and changed our API resources like so: <?php
use Illuminate\Http\Resources\Json\JsonResource;
class OwnerResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
- 'items' => ItemResource::collection($this->items),
+ 'items' => ItemResource::collectionWith($this->items, [
+ 'owner' => $this->resource,
+ ]),
];
}
} Now the |
Beta Was this translation helpful? Give feedback.
-
I see a memory issue here. Maybe I'm wrong, but if you have 1000 children, you will be storing in each of them the same parent. So if your case has small amount of children your solution suits your case, but for general purpose... What do you think? You can test like:
Also if this would be the default behaviour, then when responding in json on get /owners?with=items you would get the owner with a property items: [] and on each item the owner again. |
Beta Was this translation helpful? Give feedback.
-
I think that Laravel could and should manage this speculation under its hood, with just I'm inclined to suggest to take your question and elevate as issue, as feature request. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Laravel Version
10.33.0
PHP Version
8.1.25
Database Driver & Version
MariaDB 10.11
Description
Eloquent does not seem to inject the parent model into related child models. This causes Eloquent to re-fetch the parent from the database whenever the child accesses its parent relation. This occurs regardless of using lazy or eager fetching. Ideally the parent model would be injected so that no further queries are made.
Steps To Reproduce
Owner
(one) andItem
(many)Beta Was this translation helpful? Give feedback.
All reactions