Md. Shougat Hossain
Md. Shougat Hossain

Reputation: 521

How to create entity relationships in slick?

I am working in a project with scala play 2 framework where i am using slick as FRM and postgres database.

In my project customer is an entity. So i create a customer table and customer case class and object also. Another entity is account. The code is given bellow

case class Customer(id: Option[Int],
                status: String,
                balance: Double,
                payable: Double,
                created: Option[Instant],
                updated: Option[Instant]) extends GenericEntity {
    def this(status: String,
       balance: Double,
       payable: Double) = this(None, status, balance, payable, None, None)
}


class CustomerTable(tag: Tag) extends GenericTable[Customer](tag, "customer"){
    override def id = column[Option[Int]]("id")
    def status = column[String]("status")
    def balance = column[Double]("balance")
    def payable = column[Double]("payable")
    def account = foreignKey("fk_customer_account", id, Accounts.table)(_.id, onUpdate = ForeignKeyAction.Restrict, onDelete = ForeignKeyAction.Cascade)

    def * = (id, status, balance, payable, created, updated) <> ((Customer.apply _).tupled, Customer.unapply)
}

object Customers extends GenericService[Customer, CustomerTable] {
    override val table = TableQuery[CustomerTable]
    val accountTable = TableQuery[AccountTable]
    override def copyEntityFields(entity: Customer, id: Option[Int],
    created: Option[Instant], updated: Option[Instant]): Customer = {
        entity.copy(id = id, created = created, updated = updated)
    }
}

Now the problem is how can i create an account object inside the customer object? Or how can i get the account of a customer?

Upvotes: 1

Views: 1050

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Slick is not ORM its just a functional relational mapper. Nested objects cannot be directly used in slick like Hibernate or any other ORMs Instead

Slick

//Usual ORM mapping works with nested objects
case class Person(name: String, age: Int, address: Address) //nested object

//With Slick
case class Address(addressStr: String, id: Long) //id primary key
case class Person(name: String, age: Int, addressId: Long) //addressId is the id of the address object and its going to the foreign key

Account object in Customer

case class Account(id: Long, ....) // .... means other fields.
case class Customer(accountId: Long, ....) 

Place accountId inside the Customer object and make it a foreign key

For more info refer to Slick example provided as part of documentation

Upvotes: 3

Related Questions