Squeryl中的关系和外键 [英] Relations and Foreign Keys in Squeryl

查看:100
本文介绍了Squeryl中的关系和外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Scala,Squeryl和MySql来构建Web应用程序.

Im using Scala, Squeryl and MySql to build a web app.

我发现将简单数据存储为字符串或整数很容易.但是,当我在对象之间建立关系并且需要使用外键时该怎么办?在我的应用程序中,我有区域和子区域,它们的属性类型为区域(它们所属的区域),所以我的区域和子区域就像这些

I found it easy to persist simple data as strings or integers. But what about when i have relations between objects and i need to use foreign keys. In my app i have areas, and sub areas which have an attribute of type Area (Area where they belong) so my Area and Subarea are like these

   class Area(
            var idArea: String,

            @BeanProperty
            var name:String,
            @BeanProperty
            var letter: String,
            @BeanProperty
            var color: String
            )
  extends Idable {
  def this() = this("","", "","")

}

class SubArea(var idSubArea: String,
              @BeanProperty
              var name: String,

              @BeanProperty
              var area:Area

               ) extends Idable {

  def this() = this("","",null )

我如何定义架构,以便我的SubArea表具有Area ID,即我的Area Table的外键? 目前,我的SubArea模式就是这样

How do i define the schema, so my SubArea table has an Area id, foreign key to my Area Table?? For the time being my SubArea schema is like these

object SubAreaSchema extends Schema {

  val subAreas=table[SubArea]
  on(subAreas)(subArea => declare(
    subArea.id is (autoIncremented),
    subArea.name is (unique)
  ))
}

推荐答案

您可以通过以下方式在架构中定义关系:

You can define the relation in your schema with:

val areaToSubAreas = oneToManyRelation(areas, subAreas).via((a,sA) => s.idArea === sa.areaId) 

要使其正常工作,您需要修改SubArea类,以直接加载外键的ID,如下所示,用areaId:String.

To make that work, you would want to modify your SubArea class load the foreign key's id directly, as below with the areaId:String.

class SubArea(var idSubArea: String,
              @BeanProperty
              var name: String,

              @BeanProperty
              var areaId: String)

,然后在方法主体中,如果要访问该对象,则可以使用:

and then in the method body, if you want to have access to the object, you can use:

 def area = areaToSubAreas.right(this) 

,将生成一个查询的ManyToOne[Area],或使用headOption on转换为Option[Area].

which will yield an ManyToOne[Area] which you query, or use headOption on to convert to an Option[Area].

相反,如果需要引用Area上的子区域,则可以使用:

Conversely, if you need to reference the subareas on Area, you can use:

 def subAreas = areaToSubAreas.left(this) 

将产生一个OneToMany[Area],可以对其进行迭代,或者也可以调用toList.

which will yield an OneToMany[Area] which can be iterated over, or you can also call toList.

这篇关于Squeryl中的关系和外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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