使用Sequelize从另一个表中缺少的postgresql表中获取数据

时间:2017-09-12 10:01:35

标签: sql postgresql sequelize.js

我尝试从另一个表中缺少的Postgres SQL表中检索数据,但收到了SequelizeLoadingError

我正在尝试检索特定用户尚未租用的图书清单。

图书管理员

  getBooks(req, res) {
    const userId = req.params.userId;
    return Book
      .findAll({
        where: Sequelize.literal('RentedBook.userId IS  null'),
        include: [
          { model: RentedBook }
    ]
  })
   .then((books) => {
    if (books.length < 1) {
      res.status(400).send({
        message: 'There is no book in the database'
          });
        } else {
          res.status(201).send(books);
        }
      })
      .catch(error => res.status(404).send(error));
  },

预订模型

export default (sequelize, DataTypes) => {
  const Books = sequelize.define('Book', {
   title: {
      type: DataTypes.STRING,
      allowNull: DataTypes.FALSE,
    },
    isbn: {
      type: DataTypes.TEXT,
      required: true,
    },
    total: {
      type: DataTypes.INTEGER,
      required: true
    },
    prodYear: DataTypes.STRING,
    catId: DataTypes.INTEGER,
    cover: DataTypes.STRING,
    author: DataTypes.STRING,
    description: DataTypes.TEXT
  }, {
    classMethods: {
      associate: (models) => {
        // associations can be defined here
         Books.hasMany(models.RentedBook, {
      foreignKey: 'bookId'
        });
        Books.hasOne(models.Category, {
          foreignKey: 'catId',
          onDelete: 'CASCADE'
        });
      }
   }
  });
  return Books;
};

租借图书模型

export default (sequelize, DataTypes) => {
  const RentedBook = sequelize.define('RentedBook', {
    bookId: DataTypes.INTEGER,
    userId: DataTypes.INTEGER,
    toReturnDate: DataTypes.DATE,
    returnDate: DataTypes.DATE,
    returned: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    }
  }, {
    classMethods: {
      associate: (models) => {
    // associations can be defined here
        RentedBook.BelongsTo(models.Book, {
          foreignKey: 'bookId',
          onDelete: 'CASCADE'
        });
        RentedBook.BelongsTo(models.User, {
          foreignKey: 'userId',
          onDelete: 'CASCADE'
        });
      }
    }
  });
  return RentedBook;
};

我将非常感谢帮助我获取书籍表中存在但之前未被用户租借的书籍。

1 个答案:

答案 0 :(得分:0)

通过查询图书数据库,获取其中Username与当前登录的用户名不同的租借图书列表来解决此问题。