繁体   English   中英

Adonis.js 关系

[英]Adonis.js Relationships

我有这些表:公司、分支机构、用户、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
}

但它不起作用

这可能有效,(如果出现任何错误,您可能还需要将'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM