2016-03-31 67 views
0

我有鏈接到一個媒體表一中的hasMany關係的產品型號:Sequelize查詢其中的hasMany數爲空

Product.hasMany(models.Media, { 
    foreignKey: 'mediableId', 
    constraints: false, 
    scope: { 
     mediable: 'product' 
    }, 
    as: 'medias' 
}); 

我搜索查詢有零媒體的所有產品的一種方式,怎麼樣可以使用Sequelize完成嗎?它甚至可能沒有原始查詢?

回答

1

您可以對where子句使用原始查詢。

例如,假設您的Product模型定義如下:

module.exports = (sequelize, DataTypes) => sequelize.define('products', { 
    id: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    name: { 
     type: DataTypes.STRING, 
     allowNull: true 
    } 
}, { 
    tableName: 'products', 
    freezeTableName: true, 
    underscored: true, 
    classMethods: { 
     associate: models => { 
      models.products.hasMany(models.medias, { 
       foreignKey: 'mediable_id', 
       constraints: false, 
       scope: { 
        mediable: 'product' 
       } 
      }); 
     } 
    } 
}); 

和你Media模型定義爲:

module.exports = (sequelize, DataTypes) => sequelize.define('medias', { 
    id: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    name: { 
     type: DataTypes.STRING, 
     allowNull: true 
    }, 
    mediable: { 
     type: DataTypes.STRING, 
     allowNull: true 
    }, 
    mediable_id: { 
     type: DataTypes.INTEGER, 
     allowNull: true 
    } 
}, { 
    tableName: 'medias', 
    freezeTableName: true, 
    underscored: true, 
    classMethods: { 
     associate: models => { 
      models.products.belongsTo(models.products, { 
       foreignKey: 'id', 
       constraints: false 
      }); 
     } 
    } 
}); 

,那麼你可以查詢它是這樣的:

sequelize.sync().then(() => Promise.all([ 

    // Prepopulate Data 
    models.products.upsert({ 
     id: 1, 
     name: 'Product A' 
    }), 
    models.products.upsert({ 
     id: 2, 
     name: 'Product B' 
    }), 
    models.products.upsert({ 
     id: 3, 
     name: 'Product C' 
    }), 

    models.medias.upsert({ 
     id: 1, 
     name: 'Media A', 
     mediable: 'item', 
     mediable_id: 1 
    }), 
    models.medias.upsert({ 
     id: 2, 
     name: 'Media B', 
     mediable: 'product', 
     mediable_id: 1 
    }), 
    models.medias.upsert({ 
     id: 3, 
     name: 'Media C', 
     mediable: 'product', 
     mediable_id: 1 
    }), 
    models.medias.upsert({ 
     id: 4, 
     name: 'Media D', 
     mediable: 'product', 
     mediable_id: 2 
    }), 
    models.medias.upsert({ 
     id: 5, 
     name: 'Media E' 
    }) 

])).then(() => models.products.findAll({ 
    where: ["medias.mediable_id IS NULL OR medias.mediable != 'product'"], 
    include: [{ 
     model: models.medias, 
     required: false, 
    }] 
})).then(products => { 
    // The rest of your logic here... 
});