staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Help with Business morphMany Branch hasMany Site #112

Closed crazedVic closed 3 years ago

crazedVic commented 3 years ago

So Businesses/Consultants/Vendors can all have branches, hence morphMany.

Branches can have many Sites, Sites table has foreign key branch_id.

Branches table has branchof_type = 'App\Models\Business' and branchof_id=1

I've had no luck trying to get this working given your examples.

I would like to use $business->sites to list all sites that belong to it's branches.

Thanks for your help on this.

Here's the SQL that seems to give me what i want

select businesses.id as business_id, sites.* from sites inner join branches 
on branches.id = sites.branch_id  inner join businesses
on businesses.id = branches.branchof_id
where branches.branchof_type='App\\Models\\Business';
crazedVic commented 3 years ago

Kept messing around with it, this seems to work, could you please confirm I did this correctly?

class Business extends Model{

public function sites(){
        {
            return $this->hasManyDeep(
                'App\Models\Site',
                ['App\Models\Branch'],
                [[ 'branchof_type','branchof_id'], 'branch_id'],
            );
        }
    }
}
staudenmeir commented 3 years ago

Yes, that's correct.