【问题标题】:Where clause for associated objects with Node and sequelize使用 Node 和 sequelize 关联对象的 Where 子句
【发布时间】:2014-11-02 05:55:11
【问题描述】:

我的书籍有作者和编辑。我想查询所有标题为 '%gone% 和 author.name 为 '%paul%' 的书籍 - 我找不到有关这样做的文档,但我已经尝试了各种格式已经用谷歌搜索了。

尝试在包括上使用过滤器:

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' });
      },
...

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案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?

    【讨论】:

    • 你有没有找到合适的续集方法来做到这一点?如果是这样,您应该发布它。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 2019-08-18
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多