在scalikejdbc中加入来自同一个表的两个外键

时间:2015-03-04 18:39:16

标签: scala scalikejdbc

所以我有一个表有两个指向同一个表的FK。

例如:

带有发送方和接收方列的消息表,它们都引用用户表中的id。

当我正在编写查询以获取消息并加入时,结果对两者都是相同的,第一个。

以下是我尝试这样做的方法。

import scalikejdbc._

Class.forName("org.h2.Driver")
ConnectionPool.singleton("jdbc:h2:mem:hello", "user", "pass")

implicit val session = AutoSession

sql"""
create table members (
  id serial not null primary key,
  name varchar(64),
  created_at timestamp not null
)
""".execute.apply()

sql"""
create table message (
  id serial not null primary key,
  msg varchar(64) not null,
  sender int not null,
  receiver int not null
)
""".execute.apply()

Seq("Alice", "Bob", "Chris") foreach { name =>
  sql"insert into members (name, created_at) values (${name}, current_timestamp)".update.apply()
}

Seq(
    ("msg1", 1, 2),
    ("msg2", 1, 3),
    ("msg3", 2, 1)
) foreach { case (m, s, r) =>
  sql"insert into message (msg, sender, receiver) values (${m}, ${s}, ${r})".update.apply()
}

import org.joda.time._
case class Member(id: Long, name: Option[String], createdAt: DateTime)
object Member extends SQLSyntaxSupport[Member] {
  override val tableName = "members"
  def apply(mem: ResultName[Member])(rs: WrappedResultSet): Member = new Member(
    rs.long("id"), rs.stringOpt("name"), rs.jodaDateTime("created_at"))
}

case class Message(id: Long, msg: String, sender: Member, receiver: Member)
object Message extends SQLSyntaxSupport[Message] {
    override val tableName = "message"
  def apply(ms: ResultName[Message], s: ResultName[Member], r: ResultName[Member])(rs: WrappedResultSet): Message = new Message(
    rs.long("id"), rs.string("msg"), Member(s)(rs), Member(r)(rs))
}

val mem = Member.syntax("m")
val s = Member.syntax("s")
val r = Member.syntax("r")
val ms = Message.syntax("ms")
val msgs: List[Message] = sql"""
  select * 
  from ${Message.as(ms)}
  join ${Member.as(s)} on ${ms.sender} = ${s.id}
  join ${Member.as(r)} on ${ms.receiver} = ${r.id}
  """.map(rs => Message(ms.resultName, s.resultName, r.resultName)(rs)).list.apply()

我做错了什么还是错误?

1 个答案:

答案 0 :(得分:0)

很抱歉迟到的回复。我们有Google Group ML,我积极阅读该群组的通知。

如果您赶时间,请在那里发布stackoverflow网址。 https://groups.google.com/forum/#!forum/scalikejdbc-users-group

在这种情况下,您需要编写select ${ms.result.*}, ${s.result.*}而不是select *。请阅读此页面了解详情。 http://scalikejdbc.org/documentation/sql-interpolation.html