staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Direct property access not working

4350pChris opened this issue · comments

Hi, sorry if this is just about me not knowing Laravel well enough, but I just could not get property access to work properly.

What I mean is, I have this relationship defined in a trait:

public function item(): HasOneDeep
{
    return $this->hasOneDeepFromRelations(
        $this->positions(),
        (new Position())->node(),
        (new Part())->versions(),
        (new Version())->items(),
    )->latest('versions.valid_from');
}

It works when accessing it like $model->item()->first(), but for some reason $model->item is not defined on the class.

I don't suppose this behavior arises due to the relationship being defined in a trait?

Hi @4350pChris,

but for some reason $model->item is not defined on the class.

What happens exactly? Are you getting an error? What's the full message?

Sorry for being this vague - I thought I was getting errors, but actually $model->item simply returns null, so there's really no error message to be shown. I'm stumped as to why this is different from doing $model->item()->first(). Is there some way for me to get the SQL statement that is executed when doing dynamic property access like this?

Another thing worth mentioning is, that the class which contains the HasOneDeep relationship here has a polymorphic relationship to Position, with positions being a MorphMany relationship in the class in question.

I found out what the problem was - in the repository the position was created before the model in question which worked because the item_id was saved directly in the model (which is what I wanted to get rid of in the first place). Since the item relationship is defined in $with in the model, my guess is that it prepopulated this property for some reason before the position was created, which resulted in the query not returning any item model.

I'll close this issue since this was all on my end.