光滑的多对一映射

问题描述 投票:1回答:1

我有3个表,定义为3个案例类。卖方和买方都与地址有一对多的关系。有没有办法我可以使用地址表中的一个外键指向卖方和买方表,而不是使用两个外键?我不知道如何编写映射。这是我得到的:

case class Seller(id: Long, name: String)
case class Buyer(id: Long, name: String)
case class Address(id: Long, street: String, city: String, userId: Long)

class SellerTableDef(tag: Tag) extends Table[Seller](tag, "seller") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  override def * = (id, name) <> (Seller.tupled, Seller.unapply)
}

class BuyerTableDef(tag: Tag) extends Table[Seller](tag, "buyer") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  override def * = (id, name) <> (Buyer.tupled, Buyer.unapply)
}

class AddressTableDef(tag: Tag) extends Table[Address](tag, "address") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def street = column[String]("street")
  def city = column[String]("city")
  def userId = column[Long]("user_id")

  //!!!Can I use one foreign key to point to both the Seller and the Buyer table?!!! 
  def user = foreignKey("user_FK", userId, ???)(_.id)
}

非常感谢。

scala slick
1个回答
0
投票

这似乎更像是一个DB设计问题。

通常的做法是拥有买方表,卖方表,地址表。然后每个买方/卖方行都有一个地址ID FK。地址表不应具有买方/卖方ID,因为该地址可能属于多行

评论后编辑:

在这种情况下,您需要一个BuyerAddress(与SellerAddress相同)表,其中包含buyerId和addressId,它将保留每个买方的所有地址(buyerId,addressId)

BuyerTable:id,name SellerTable:id,name AddressTable:id,street,city,userId BuyerAddressTable:buyerId,addressId SellerAddressTable:sellerId,addressId

© www.soinside.com 2019 - 2024. All rights reserved.