真的隨筆記。
Table 做壞了想重新開
- 先撤銷所有的 migation
1
| npx sequelize-cli migrate:undo:all
|
- 重新建立
1
| npx sequelize-cli db:migrate
|
一些設定 Model 時會用到的屬性
1 2 3 4 5
| autoIncrement: true allowNull: false primaryKey: true unique: true defaultValue: false
|
一些跟 Model 操作相關的 methods
找總數量
1 2 3 4 5 6 7 8 9 10 11
| Post.count({ where: { title: '123' } }) .then(post => { console.log('success', post); }) .catch(err => { console.log('failed', err); })
|
對被 include 的 model 做 where 查詢
1 2 3 4 5 6 7 8
| const category = await Category.findOne({ where: { id }, include: [{ model: Post, where: { isDeleted: 0 }, }], });
|
對被 include 的 model 做 order 排序
1 2 3 4 5 6 7 8 9 10
| const category = await Category.findOne({ where: { id }, order: [[Post, 'id', 'DESC']], include: [{ model: Post, where: { isDeleted: 0 }, }], });
|
對被 include 的 model 做 offset 和 limit
建議加上一個 separate
的屬性,不然巢狀有時候會有 bug:
1 2 3 4 5 6 7 8 9 10 11
| const category = await Category.findOne({ where: { id }, include: [{ model: Post, where: { isDeleted: 0 }, separate : true, order: [['createdAt', 'DESC']], limit, offset }], });
|