[英]Adonis.js Relationships
I have these tables: companies, branches, users, users_branches我有这些表:公司、分支机构、用户、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
用户可以链接到在users_branches数据透视表中捕获的分支
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这可能有效,(如果出现任何错误,您可能还需要将
'user_id'
更改为'id'
,同时启用 DEBUG 并观察查询
const companies = await Company.query()
.whereHas('branches', branchesQuery => {
branchesQuery.whereHas('users', uq => {
uq.where('user_id', 1)
})
})
.fetch()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.