我有以下表:公司、分支机构、用户、users_branches
每个分支都链接到公司。可以将用户链接到users_branches枢轴表中捕获的分支。
在公司的索引和显示方法中,我只需要显示为用户可以访问的公司,也就是说,仅显示链接到他注册的任何分支的公司。你能帮帮我吗?
我今天要讲的是这个,非常基本的,列出了所有的东西:
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
}我试过用另外两种方法:
async index ({ auth }) {
const { user } = auth
return user.branches().company().fetch()
}和
async index () {
const companies = await Company.query()
.whereHas('branches', branchesQuery => {
branchesQuery.wherePivot('user_id', 1)
})
.fetch()
return companies
}但不起作用
发布于 2020-03-08 12:07:39
这可能有效,(如果出现任何错误,还需要将'user_id'更改为'id',还可以启用调试并查看查询。
const companies = await Company.query()
.whereHas('branches', branchesQuery => {
branchesQuery.whereHas('users', uq => {
uq.where('user_id', 1)
})
})
.fetch()https://stackoverflow.com/questions/60526877
复制相似问题