2016-11-22 45 views
1

我創建一個DB模式:如何設置主鍵類型與此命令通過<a href="https://github.com/sequelize/cli" rel="nofollow noreferrer">Sequelize CLI</a>通過Sequelize CLI到UUID

sequelize model:create --name User --attributes "firstname:string, lastname:string" 

這將創建相應的遷移腳本:

'use strict'; 
module.exports = { 
    up: function(queryInterface, Sequelize) { 
    return queryInterface.createTable('Users', { 
     id: { 
     allowNull: false, 
     autoIncrement: true, 
     primaryKey: true, 
     type: Sequelize.INTEGER 
     }, 
     firstname: { 
     type: Sequelize.STRING 
     }, 
     lastname: { 
     type: Sequelize.STRING 
     }, 
     createdAt: { 
     allowNull: false, 
     type: Sequelize.DATE 
     }, 
     updatedAt: { 
     allowNull: false, 
     type: Sequelize.DATE 
     } 
    }); 
    }, 
    down: function(queryInterface, Sequelize) { 
    return queryInterface.dropTable('Users'); 
    } 
}; 

如圖所示,主鍵被設置爲integer

有沒有一種方法可以讓CLI默認使用UUID

回答

1

您必須手動編輯生成的文件,將Sequelize.INTEGER更改爲Sequelize.UUID,然後刪除autoIncrement: true屬性幷包含此defaultValue: uuid()

npm install uuid

所以,你的模型應該是這樣的:

const uuid = require('uuid/v4'); // ES5 

'use strict'; 

module.exports = { 
    up: function(queryInterface, Sequelize) { 
    return queryInterface.createTable('Users', { 
     id: { 
     allowNull: false, 
     primaryKey: true, 
     type: Sequelize.UUID, 
     defaultValue: uuid() 
     }, 
     firstname: { 
     type: Sequelize.STRING 
     }, 
     lastname: { 
     type: Sequelize.STRING 
     }, 
     createdAt: { 
     allowNull: false, 
     type: Sequelize.DATE 
     }, 
     updatedAt: { 
     allowNull: false, 
     type: Sequelize.DATE 
     } 
    }); 
    }, 
    down: function(queryInterface, Sequelize) { 
    return queryInterface.dropTable('Users'); 
    } 
}; 
+0

這似乎並不爲MySQL的工作。在插入時,我會得到:「字段ID」沒有默認值「 – kequc

+0

您可以使用npm包來生成UUID。 ''npm install uuid''或'npm install uuidv4' ES5 'const uuidv4 = require('uuid/v4');'或'const uuid = require('uuidv4')' 'uuidv4();'或' UUID()' ES6 '進口從 'UUID/V4' UUID;' UUID() 做,即與所需/進口'uuid'通話更換'defaultValue'屬性的值。這樣做會允許在每次保存時自動生成UUID。 –

+0

只是一個提示。我覺得我在Bookshelfjs和Knex方面取得了一些成功,但其他困擾我的關於Sequelize的問題是使用unix時間戳創建/更新的困難。 – kequc

相關問題