2017-02-10 86 views

回答

0

好的車型同步功能,告訴Keval我需要同步()的車型,所以我複製從sequelize.sync()/粘貼代碼,並改變它:

if (config.sync && config.sync != 'false') { 
    let models = []; 
    sequelize.modelManager.forEachModel(function(model) { 
    if (model && model.options.sync !== false) { 
     models.push(model); 
    } else { 
     // DB should throw an SQL error if referencing inexistant table 
    } 
    }); 
    return Sequelize.Promise.each(models, function(model) { 
    return model.sync(config.sync); 
    }); 
} 
3

我用很卡的方法當我想創建和使用帶有Sequelize的視圖時,我會回到十字軍的答案。在這種情況下,我不希望Sequelize嘗試同步視圖,因爲它會導致創建表。要做到這一點,我添加以下到Sequelize模式:

var MyView = sequelize.define("MyView", { 
    status: { type: DataTypes.TEXT }, 
}, 
{ 
    doNotSync: true, 
    tableName: "myDatabaseView", // The actual view name in database 
    classMethods: { 
    createView: function(models) { 
     return sequelize.query("CREATE OR REPLACE VIEW myDatabaseView ...;"); 
    } 
}); 

現在我有設置我需要確保當我創建數據庫的意見,不包含在該createView方法被調用每個觀點。

var tables = []; 
sequelize.modelManager.forEachModel(m => { 
    if (m.options.doNotSync !== true) { 
     tables.push(m); 
    }    
}); 

return Sequelize.Promise.each(tables, t => { 

    return t.sync({force: true}); 

}).then(_ => { 

    var views = []; 
    sequelize.modelManager.forEachModel(m => { 
     if (m.options.doNotSync && m.createView) { 
     views.push(m); 
     }    
    }); 

    return Sequelize.Promise.each(views, v => { 

    return v.createView(sequelize.models); 

    }); 

}); 

此外,爲了安全起見,我添加了鉤子以防止在視圖上使用任何create/update/delete操作。

hooks: { 
    beforeBulkCreate: throwNotAllowedError, 
    beforeBulkDestroy: throwNotAllowedError, 
    beforeBulkUpdate: throwNotAllowedError, 
    beforeCreate: throwNotAllowedError, 
    beforeDestroy: throwNotAllowedError, 
    beforeUpdate: throwNotAllowedError 
} 

throwNotAllowedError是一個簡單的功能

function throwNotAllowedError() { 
    throw new Error("Operation not allowed on a view"); 
} 

希望有所幫助。獲得對Sequelize的看法使我們在項目的生產力上獲得了巨大的提升。

而且您仍然可以從視圖中創建關係和關聯,從而允許您使用include:[]表示法將其他表添加到視圖查詢中。