具有Node和sequelize的关联对象的Where子句

时间:2014-09-08 22:21:34

标签: node.js sequelize.js

我有书籍,有作者和编辑。我想查询所有标题为'%off%和author.name的书籍,如'%paul%' - 我无法找到关于这样做的文档,但我已根据我用Google搜索的内容尝试了各种格式。

尝试使用过滤器包括:

var includes = [
   {"model": db.User, as: 'Author', through: {"where": {"name": { like: '%paul%'}}}}
];

var filter = { title: { like: '%gone%'}};

return Book.findAll({ include: includes, order: 'id desc', where: filter});

虽然对标题的限制有效,但作者姓名被忽略(没有错误)。

没有'到'的变化(结果相同 - 不影响结果集):

var includes = [
   {"model": db.User, as: 'Author', "where": {"name": { like: '%paul%' } } }
];

我主动认为它可能会起作用(导致错误):

var filter = { title: { like: '%gone%'}, 'author.name' : { like : '%paul%' } };

任何有关文档的线索或指示可以帮助我做到这一点?

感谢。

型号:

var User = sequelize.define('User', {

    name: {
      type: DataTypes.STRING
    },
...
    classMethods: {
      associate: function (models) {
        User.hasMany(Book, { as: 'Author', foreignKey: 'author_id' });
        User.hasMany(Book, { as: 'Editor', foreignKey: 'editor_id' });
      },
...
}


var Book = sequelize.define('Book', {
    title: {
      type: DataTypes.STRING,
      len: [20]
    },
...
    classMethods: {
      associate: function (models) {
        Book.belongsTo(User, { as: 'Author', foreignKey: 'author_id' });
        Book.belongsTo(User, { as: 'Editor', foreignKey: 'editor_id' });
      },
...

1 个答案:

答案 0 :(得分:1)

我通过删除' as'在预订的用户关联中:

User.hasMany(Book, { foreignKey: 'author_id' });
User.hasMany(Book, { foreignKey: 'editor_id' });

然后我可以按预期过滤:

var includes = [
  {model: db.User, as: 'Author'},
  {model: db.User, as: 'Editor'}
];    
var filter = { title: { like: '%gone%'}, 'Author.name' : { like : '%paul%' } };
return Book.findAll({ include: includes, order: 'id desc', where: filter});

它有助于打开SQL语句的日志记录,如下所述:How can I see the SQL generated by Sequelize.js?