簡體   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