1

所以我有一张桌子,有两个 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()

我做错了什么还是错误?

4

1 回答 1

0

抱歉回复晚了。我们有 Google Group ML,我积极阅读来自该组的通知。

当您赶时间时,请在此处发布 stackoverflow URL。https://groups.google.com/forum/#!forum/scalikejdbc-users-group

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

于 2015-03-26T09:45:13.183 回答