鍍金池/ 問答/數(shù)據(jù)庫/ sequelize級(jí)聯(lián)刪除

sequelize級(jí)聯(lián)刪除

環(huán)境

node.js+sequelize+mysql

業(yè)務(wù)背景

mysql數(shù)據(jù)庫中,有兩個(gè)表已經(jīng)建立了外鍵關(guān)系.
這個(gè)時(shí)候我想刪除主表上的數(shù)據(jù)
但是sequelize提供的destroy方法不行

表結(jié)構(gòu)

  • 班主任表:master(id,name)
  • 學(xué)生表:student(id,master_id,name)

問題

通過Teacher.destroy({where: {id: 2})刪除的時(shí)候,會(huì)報(bào)錯(cuò).因?yàn)槭艿酵怄I約束..沒辦法刪除

sequelize有內(nèi)置的級(jí)聯(lián)刪除么?
或者用 query方法,怎么寫sql代碼呢?

回答
編輯回答
綰青絲

我使用的方式 獲取實(shí)例和關(guān)聯(lián)的實(shí)例執(zhí)行刪除

也許是這樣
teacher = Teacher.findById(2)
students = teacher.getStudents()
for (let student of students) { student.destory() }
teacher.destory()

這是有效的。剛剛學(xué)習(xí)。也許還有更好的方式 :)

2018年4月23日 20:00
編輯回答
深記你
sequelize.define(name, { attributes }, {
  hooks: {
    beforeDestroy: function () {
      //在這里能做你愛做的事情
    },
    beforeValidate: [
      function () {},
      function() {} // Or an array of several
    ]
  }
})

還有,看到belongsTo 的參數(shù)有:

  • options.hooks,
  • options.as,
  • options.foreignKey,
  • options.targetKey,
  • options.onDelete:看一下這個(gè)能不能幫到你
  • options.onUpdate,
  • options.constraints:看一下這個(gè)能不能幫到你
2017年12月5日 18:44