Sequelize findAndCount所有行不在关联

时间:2018-01-18 16:10:35

标签: mysql node.js sequelize.js

有两个表格: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引起的。

2 个答案:

答案 0 :(得分:1)

使用包含

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

答案 1 :(得分:0)

带有分页的节点分页
客户需要提供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); });