Skip to content

Child relationships don't work with a parent collection. #122

@lmonterocreaticagency

Description

@lmonterocreaticagency

Hello,

I'm taking the liberty of opening an issue following a potential problem that I'll describe below:

I have a parent model that I'm going to call Vehicle. Parent has two children, car and truck

class Vehicle extends Model
{
    use HasChildren;

    protected $with = [
        'tire';
    ];

    protected $childTypes = [
        'CAR'     => Car::class,
        'TRUCK'    => Truck::class,
    ];

   public function tire()
   {
       return $this->hasOne(Tire::class);
   }
}

class Car extends Vehicle
{
    use HasParent;

    protected $with = [
        'owner'
    ];

   public function owner()
   {
       return $this->hasOne(Owner::class);
   }
}

class Truck extends Vehicle
{
    use HasParent;
}

When I want to retrieve a collection of all children, the with array is not merged with the parent model, so I only retrieve my "tire" relationship.

So for the moment I've had to add logic when retrieving a child model from a list to force the loading of parent/child relationships.

        static::retrieved(function ($model) {
            // Merge with parent and child
            $parent = new ($model->getParentClass());
            $with = array_unique(array_merge($parent->with, $model->with));
            $model->with = $with;

            if ($model->with) {
                $model->load($model->with);
            }
        });

Do you have another solution or is this the right way to go?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions