Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lmonterocreaticagency opened this issue Dec 8, 2023 · 2 comments
Open

Comments

@lmonterocreaticagency
Copy link

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?

@Smoggert
Copy link
Contributor

As you are retrieving the models from Vehicle, any initial configuration is going to be that of Vehicle.
Even if it would take into account the children with, an overwrite would be more conform than a merge since this is how inheritance works.

If you want child specific behavior, specifically query that model.
If you want parent specific behavior, specifically query that model.

I wouldn't consider this a bug or an issue.

@driftingly
Copy link
Member

Unfortunately we can't do something similar to what @gcavanunez did in #120

with is used in the following way:

    public function newQueryWithoutScopes()
    {
        return $this->newModelQuery()
            ->with($this->with)
            ->withCount($this->withCount);
    }

Not sure how we would update this on child models.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants