HotelCalifornia's avatar

Relationship through multiple tables and join tables

I have an Organisation table which has many Users.

Those Users can have many Properties via a pivot table.

What I'd like to do is use Eloquent to select all the properties that 'belong' to an Organisation (i.e. properties created by an organisation's users).

Organisations
ID
Users
Organisation ID
Properties
ID

And the pivot table:

property_user
property_id
user_id

I realise I could do this with the query builder but currently I've managed to use only Eloquent relationships in models.

I've also come across eloquent-has-many-deep (https://github.com/staudenmeir/eloquent-has-many-deep) but I'm just wondering if I should maybe just give up and use the query builder instead?

0 likes
3 replies
nexxai's avatar

Just use a HasManyThrough relationship on the Organzation model, through the User model.

Organization.php

public function properties(): HasManyThrough
{
	return $this->hasManyThrough(Property::class, User::class);
}

Then you can access it like: Organization::with('properties')->get();

kevinbui's avatar

HasManyThrough might not work in this scenario, this is like a many-to-many relationship between Users and Properties. You can simply query relationship existence:

$organisation = Organisation::find(...);

Property::whereHas('users', fn ($query) => $query->where('organisation_id', $organisation->id))->get();
Thunderson's avatar

check "staudenmeir eloquent-has-many-deep" on google, this package can help you

Please or to participate in this conversation.