【问题标题】:Sequelize findAndCountAll rows not in associations对不在关联中的 findAndCountAll 行进行续集
【发布时间】:2018-06-27 18:44:09
【问题描述】:

有两个表:Books,列出可用书籍,BorrowedBooks,列出当前借阅的书籍。我只想检索当前可用(未借阅)的书籍,提供分页和总数。

我会使用 Sequelize 提供的方法findAndCountAll,它真的很容易使用并且可以完成大部分工作,但是它不能正常工作。我尝试了以下代码,使用findAll 方法,它可以正常工作。

Books.findAll({
    where: { '$BorrowedBooks.bookId$': null },
    include: [BorrowedBooks]
}).then(...).catch(...);

然后我将方法改为findAndCountAll,以获取元素的总数并提供分页。

Books.findAndCountAll({
    where: { '$BorrowedBooks.bookId$': null },
    include: [BorrowedBooks],
    offset: offset,
    limit: limit,
    distinct: true
}).then(...).catch(...);

此版本产生错误Unknown column 'BorrowedBooks.bookId' in 'where clause'

编辑

生成的带有不起作用的代码的查询如下:

SELECT 
    `books`.*,
    `borrowedBooks`.`bookId` AS `borrowedBooks.bookId`,
    `borrowedBooks`.`userId` AS `borrowedBooks.userId`,
FROM
    (SELECT 
        `books`.`id`,
        `books`.`title`,
        `books`.`author`,
        `books`.`isbn`
    FROM
        `books` AS books`
    WHERE
        (SELECT 
                `bookId`
            FROM
                `borrowedBooks`
            WHERE
                (`borrowedBooks`.`bookId` = `books`.`id`
                    AND `borrowedBooks`.`bookId` IS NULL)
            LIMIT 1) IS NOT NULL
    LIMIT 0 , 10) AS `books`
        INNER JOIN
    `borrowedBooks` ON `books`.`id` = `borrowedBooks`.`bookId`
        AND `borrowedBooks`.`bookId` IS NULL;

如果我直接写下查询,我会这样做:

SELECT * FROM `books`
LEFT OUTER JOIN `borrowedBooks` ON `books`.`id` = `borrowedBooks`.`bookId`
WHERE `borrowedBooks`.`bookId` IS NULL

我认为错误是由于 Sequelize 使用的 INNER JOIN 造成的。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    正确使用包含的语法

    Books.findAll({
        include: [{
          model: BorrowedBooks,
          where: {
            bookId: null
          }
        }],
        offset: offset,
        limit: limit,
        distinct: true
    }).then(...).catch(...);
    

    【讨论】:

    • 我测试了这个版本,给我返回了一个空列表,但是 Book 表中有行没有在 BorrowedBook 表中引用。
    • 没有产生错误,但这不是所需的输出。如果我不依赖 Sequelize,我将添加生成的查询和我将使用的查询。
    • 如果 bookId 是外键,那么它永远不会是 null 值......那么你怎么能在 where 子句中使用 bookId 作为 null
    • 如果我执行 LEFT JOIN,对于所借书籍中未引用的书籍中的每一行, bookId 将为 NULL。正如我在问题中所说,我认为问题与 Sequelize 使用的 INNER JOIN 子句有关。使用时,不会检索 bookId 为 NULL 的行。
    • @oniramarf 也显示模型和关联部分
    【解决方案2】:

    节点分页与续集
    客户端需要在查询中提供 page 和 pageSize
    Pass distinct: true ,它将按照您的意愿工作。您还将包含数据。
    const page = 1 const pageSize = 2 const offset = page * pageSize const limit = offset + pageSize return model .findAll({ attributes: [], include: [{}], distinct: true, limit, offset }) .then((tasks) => res.status(200).send(tasks)) .catch((error) => { console.log(error); res.status(400).send(error); });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多