Insert foreign key data using Slick

I am having a problem with a request to insert an insert using slick. I want to insert a row, return the primary key, and then insert a new row with the foreign key into the row just inserted.

I tried using flatmap to link the result of the first insert into the second insert, however the following code seems to only perform the first insert into the "users" table, not the second insert into the "lists"

Sample code below, in advance for your help!

package com.example.jdbc

import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object DatabaseControllerMin {

  lazy val db = Database.forConfig("postgres")

  lazy val recreateTables = DBIO.seq(
    // drop the old tables
    (users.schema ++ lists.schema).drop,
    // Create the tables, including primary and foreign keys
    (users.schema ++ lists.schema).create
  )

  class Users(tag: Tag) extends Table[(Int, String)](tag, "users") {

    def id = column[Int]("user_id", O.PrimaryKey, O.AutoInc)

    def name = column[String]("name")

    def * = (id, name)
  }

  lazy val users = TableQuery[Users]

  class Lists(tag: Tag) extends Table[(Int, String, Int)](tag, "lists") {

    def id = column[Int]("list_id", O.PrimaryKey, O.AutoInc)

    def name = column[String]("name")

    def userId = column[Int]("user_id")

    def * = (id, name, userId)

    def user = foreignKey("users", userId, users)(_.id)
  }

  lazy val lists = TableQuery[Lists]

  def recreateDatabase = {
    try {
      val q = recreateTables andThen {
        users returning users.map(_.id) into ((user, id) => user.copy(_1 = id)) +=(0, "Tyler")
      }  flatMap {
        user => {
          lists +=(0, s"${user._2} List", user._1)
        }
      }
      db.run(q)
    } finally db.close
  }

  def main(args: Array[String]) {
    recreateDatabase onComplete {
      case Success(x) => {
        println("Success!!!")
      }
      case Failure(t) => {
        println("Failure")
        t.printStackTrace
      }
    }
  }
}
+4
source share

All Articles