Answer the question
In order to leave comments, you need to log in
Laravel how to create relationship across multiple tables?
Essence such, is the table of users and the table of branches. Many-to-many relationship (belongsToMany)
There is a Warehouse table, it refers to the branch as many-to-one (belongsTo)
And there is a Tariffs table, it refers to the warehouse as many-to-one (belongsTo)
Branches to which the user is bound, I can get it like
Auth::user()->branches()->get()
How do I get the warehouses that belong to the branches to which the user has access?
And even trickier: how to get rates that apply to warehouses that apply to branches that the user has access to?
Answer the question
In order to leave comments, you need to log in
HasMany Through
user hasMany warehouses through branches with
prices
$user->branches()
->with('warehouses.prices')
->get();
Warehouse::whereHas('branche', function ($query) {
$query->where('user_id', Auth::id());
})
->get();
I decided in the end not to be too smart, because. time is very limited, I added functions to the user model that, through joins, pull out the id of all entities associated with users through several tables
public function stores(){
return Store::join('branches', 'stores.branch_id', '=', 'branches.id')->
join('user_branches', 'branches.id', '=', 'user_branches.branch_id')->
join('users', 'user_branches.user_id', '=', 'users.id')->
select('stores.id as id')->
where('users.id', $this->id);
}
public function rates(){
return Rate::join('stores', 'rates.store_id', '=', 'stores.id')->
join('branches', 'stores.branch_id', '=', 'branches.id')->
join('user_branches', 'branches.id', '=', 'user_branches.branch_id')->
join('users', 'user_branches.user_id', '=', 'users.id')->
select('rates.id as id')->
where('users.id', $this->id);
}
->whereIn('id', Auth::user()->rates()->pluck('id'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question