Y
Y
Yariy2021-01-29 11:54:23
Laravel
Yariy, 2021-01-29 11:54:23

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

2 answer(s)
J
jazzus, 2021-01-29
@jazzus

HasMany Through
user hasMany warehouses through branches with prices

$user->branches()
    ->with('warehouses.prices')
    ->get();

Here you will need to fork branches and each will have $branch->warehouses and a chain.
Or request in warehouses
Warehouse::whereHas('branche', function ($query) {
    $query->where('user_id', Auth::id());
})
->get();

prices similarly

Y
Yariy, 2021-02-01
@Yariy

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);
    }

and add a filter by id
->whereIn('id', Auth::user()->rates()->pluck('id'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question