I have DB structure:
user
user_id
office
office_id
property
property_id
office_user
office_user_id
office_id
user_id
office_user_property
office_user_id
property_id
Is there way to acess to Property model from User model via belongsToMany?
CodePudding user response:
What you are looking for is the hasManyThrough
(https://laravel.com/docs/9.x/eloquent-relationships#has-many-through), but it only work for one connection in between, and you have two.
What you could do is define a hasManyThrough
relation between user and office_user_property and define a hasOne
relation between office_user_property and property
CodePudding user response:
belongsToMany
refers to Many To Many. This relationship for your case defines that has many properties, while a property is owened by many users. In a nutshell three database tables can be used to define this relationship. properties
table, users
table, and user_property
table. where the user_property
table contains user_id
and property_id
columns.
In the user
model, the relationship can be defined as:
/.../
public funciton properties(){
return $this->belonsToMany('App\Property');
}
To access properties for a user:
$user = App\User::find(1);
foreach ($user->properties as $property) {
//
}
Ref: Laravel 5.2 Docs