光滑的多对多仓库

时间:2018-11-25 07:01:41

标签: scala join many-to-many slick

这些是随机的客户和课程库

@Singleton
class CourseRepository @Inject()(dbConfigProvider: DatabaseConfigProvider)(implicit ec: ExecutionContext) {

  // We want the JdbcProfile for this provider
  val dbConfig = dbConfigProvider.get[JdbcProfile]

  import dbConfig._
  import profile.api._

  class CourseTable(_tableTag: Tag) extends Table[Course](_tableTag, "course") {
    def * = (courseId, name) <> ((Course.apply _).tupled, Course.unapply)

    def ? = (Rep.Some(courseId), Rep.Some(name)).shaped.<>({ r => import r._; _1.map(_ => (Course.apply _).tupled((_1.get, _2.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

    val courseId: Rep[Int] = column[Int]("course_id", O.PrimaryKey)
    val name: Rep[String] = column[String]("name", O.Length(255, varying = true))
  }

  private val courses = TableQuery[CourseTable]

  def create(course: Course) = db.run {
    courses += course
  }

  def findById(courseId: Int): Future[Course] = db.run {
    courses.filter(_.courseId === courseId).result.head
  }

  def createMany(courseList:Seq[Course]) = db.run{
    courses ++= courseList
  }

  def list(): Future[Seq[Course]] = db.run {
    courses.result
  }
}

@Singleton
class ClientRepository @Inject()(dbConfigProvider: DatabaseConfigProvider)(implicit ec: ExecutionContext) {
  // We want the JdbcProfile for this provider
  private val dbConfig = dbConfigProvider.get[JdbcProfile]

  import dbConfig._
  import profile.api._

    private class ClientTable(tag: Tag) extends Table[Client](tag, "client") {
      def * = (userId, name) <> ((Client.apply _).tupled, Client.unapply)

      def ? = (Rep.Some(userId), Rep.Some(name)).shaped.<>({ r => import r._; _1.map(_ => (Client.apply _).tupled((_1.get, _2.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

      val userId: Rep[Int] = column[Int]("client_id", O.PrimaryKey, O.AutoInc)
      val name: Rep[String] = column[String]("name", O.Length(255, varying = true))
    }

  private val people = TableQuery[ClientTable]

  def create(client: Client) = db.run {
    people += client
  }

  def findById(clientId: Int) = db.run {
    people.filter(_.userId === clientId).result.head
  }

  def list(): Future[Seq[Client]] = db.run {
    people.result

} }

我的问题是,我有第三个表client_course,在这里我映射了这两个表之间的多对多关系,并且要进行联接,我必须访问客户端表和课程表,但是我的client_course存储库在另一个类中,并且我不能简单地从clientrepo或courserepo访问表,所以我的问题是,我该如何编写client_course repo和访问表以进行联接查询?

示例

    for {
      (client, course) <- clients join courses
    } yield (client, course)

要做到这一点,我必须访问由其他存储库管理的客户和课程表,我是否应该将用于客户和课程的TableQuery放在我的client_course存储库中?

像这样

  private val clientCourses = TableQuery[ClientCourse]
  private val courses = TableQuery[Course]
  private val clients = TableQuery[Client]

0 个答案:

没有答案