eloquent-has-many-deep: [BUG] hasManyDeepFromRelations doesnt respect the relation constraints

consider the following relations

// User Model
public function accounts()
{
    return $this->hasMany(Account::class);
}

public function avail_accounts()
{
    return $this->accounts()->isActive();
}

public function regions()
{
    return $this->hasManyDeepFromRelations($this->accounts(), (new Account())->region())
        ->distinct()
        ->orderBy('name');
}

public function avail_regions()
{
    return $this->hasManyDeepFromRelations($this->avail_accounts(), (new Account())->region())
        ->distinct()
        ->orderBy('name');
}

// Account Model
public function region()
{
    return $this->belongsTo(Region::class);
}

when using any of regions or avail_regions, they will return the same result. however when trying accounts.region & avail_accounts.region on their own, they works correctly.

if u need more info, plz ask.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 29 (15 by maintainers)

Most upvoted comments

I released v1.15.3 with hasManyDeepFromRelationsWithConstraints():

public function avail_regions()
{
    return $this->hasManyDeepFromRelationsWithConstraints([$this, 'avail_accounts'], [new Account(), 'region'])
        ->distinct()
        ->orderBy('name');
}

Thanks, but I want to release a method that also covers more complex edge cases. That’s the reason I haven’t released such a helper yet.

You need to take the relationship with constraints (e.g. $this->avail_accounts()) and add its additional constraints (from the base query) to the hasManyDeepFromRelations() relationship’s base query. In this case, there’s one constraint and one binding.

I see. I’ll think about a workaround.