NodeJS 把表连起来

pkln4tw6  于 2023-01-04  发布在  Node.js
关注(0)|答案(1)|浏览(95)

工作在一个已经安装的数据库,也是新的续集。我有像四个表
1.顾客
1.图书馆
1.书籍
1.节录
excerpt具有来自books的冗余book_idbooks具有来自library的冗余library_id,library具有来自customer的冗余customer_id。它们在数据库中未被声明为外来,但它有点像外键类型,我在点击orm函数时进行关联。

    • 我的问题:*我有一个customer_idbook_id,我必须根据book_id获取excerpt记录,但必须转到数据库顶部以匹配customer_id。(对于多租户)流程为: 摘录〉图书标识-图书〉图书馆标识-图书馆〉客户标识-客户 *

我已经写了这个代码,但它不工作

async read_book_id(customer_id, book_id) {
    const excerpts = await this.model.findAll({  // this.model being the excerpt model
      where: { book_id: book_id},
      include: [
        {
          model: this.db.Books,
          association:
             this.model.belongsTo(this.db.Books, {
                  foreignKey: 'book_id',
                }),
          where: { book_id: book_id},
          include: [
            {
              model: this.db.Library,
              association: this.model.belongsTo(this.db.Library, {
                foreignKey: 'library_id',
              }),
              where: { customer_id: customer_id },
            },
          ],
        },
      ],
    });

基本上,这是我写的另一个代码的扩展,它对我很有效。如果我只检查上面一个级别,它对我很有效,例如
//读取基于library_id的书籍

async read(customer_id, library_id) {
    const books= await this.model.findAll({
      where: {
        library_id: library_id,
      },
      include: [
        {
          model: this.db.Library,
          association: this.model.belongsTo(this.db.Library, {
            foreignKey: 'library_id',
          }),
          where: { customer_id: customer_id },
        },
      ],
    });
  }

这对我来说很好。
你能告诉我如何运行第一个代码块吗?

uxhixvfz

uxhixvfz1#

假设你已经注册了所有的关联,就像我在上面的评论中建议的那样,你需要在include选项中指明正确的模型沿着正确的条件:

const excerpts = await this.model.findAll({  // this.model being the excerpt model
      where: { book_id: book_id},
      include: [
        {
          model: this.db.Books,
          include: [
            {
              model: this.db.Library,
              where: { customer_id: customer_id },
              required: true
            },
          ],
        },
      ],
    });```

相关问题