I have these tables: companies, branches, users, users_branches
Every branch is linked to a company . The user can be linked to a branch that captures in the users_branches pivot table
In the index and show methods of the company I need to display only as companies that the user has access to, that is, only as companies that are linked to any branch that he is registered with. Can you help me?
What I have today is this, very basic and listing everything:
async index () {
const companies = await Company.all()
return companies
}
async show ({ params }) {
const company = await Company.findOrFail(params.id)
await company.load('branches')
return company
}
I've tried to do it in two other ways:
async index ({ auth }) {
const { user } = auth
return user.branches().company().fetch()
}
and
async index () {
const companies = await Company.query()
.whereHas('branches', branchesQuery => {
branchesQuery.wherePivot('user_id', 1)
})
.fetch()
return companies
}
But it does not work
This might work, (you may also need to change 'user_id'
to 'id'
if it gives any error, also enable DEBUG and watch the query
const companies = await Company.query()
.whereHas('branches', branchesQuery => {
branchesQuery.whereHas('users', uq => {
uq.where('user_id', 1)
})
})
.fetch()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.