Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do cascade delete for foreign key in slick

Tags:

scala

slick

In slick, how to do cascade deletion for foreign key? Is there any way to specify this on the schema level, or do it when delete is called after the query?

like image 398
Qiang Li Avatar asked Mar 20 '14 16:03

Qiang Li


1 Answers

I updated the docs: https://github.com/slick/slick/pull/721/

A foreign key constraint can be defined with a Table’s foreignKey method. It first takes a name for the constraint, the referencing column(s) and the referenced table. The second argument list takes a function from the referenced table to its referenced column(s) as well as ForeignKeyAction for onUpdate and onDelete, which are optional and default to NoAction. When creating the DDL statements for the table, the foreign key definition is added to it.

class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
  def supID = column[Int]("SUP_ID")
  //...
  def supplier = foreignKey("SUP_FK", supID, suppliers)(_.id, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Cascade)
  // compiles to SQL:
  //   alter table "COFFEES" add constraint "SUP_FK" foreign key("SUP_ID")
  //     references "SUPPLIERS"("SUP_ID")
  //     on update RESTRICT on delete CASCADE
}
like image 104
cvogt Avatar answered Sep 22 '22 14:09

cvogt