有两个表: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。

最佳答案

使用正确的语法包括

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

09-25 15:48