如何创建光滑的实体关系? [英] How to create entity relationships in slick?

查看:91
本文介绍了如何创建光滑的实体关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与scala play 2框架一起工作的项目中,在这里我将使用slick作为FRM和postgres数据库.

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?

推荐答案

Slick不是ORM,它只是一个功能性的关系映射器.嵌套对象不能像Hibernate或任何其他ORMs一样直接在slick中使用

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

光滑

//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

客户中的帐户对象

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

accountId放置在Customer对象内,并使其成为外键

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

有关更多信息,请参阅作为文档一部分提供的Slick示例

这篇关于如何创建光滑的实体关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆