2017-05-30 11 views
0

Slick(2.1)では、1対多の関係で2つのテーブルを結合する簡単なクエリがあります。おおよそ次のように定義されます。Slick.io - 結合されたテーブルの処理

class Users(tag: Tag) extends Table[ User ](tag, "users") 
    // each field here... 
    def * = (id, name).shaped <> (User.tupled, User.unapply) 

class Items(tag: Tag) extends Table[ Item ](tag, "items") 
    // each field here... 

    // foreign key to Users table 
    def userId = column[ Int ]("user_id") 
    def user_fk = foreignKey("users_fk", userId, Users)(_.id) 
    def * = (id, userId.?, description).shaped <> (Item.tupled, Item.unapply) 

1人のユーザーが複数のアイテムを持つことができます。私がマーシャリングしたいユーザーケースクラスは次のようになります...

case class User(id: Option[Int] = None, name:String, items:Option[List[Item]] = None) 

私は、暗黙的にデータベースを照会、次のように参加...

for{ 
    u <- Users 
    i <- Items 
     if i.userId === u.id 
    } yield(u, i) 

この細かい「走ります」。ただし、クエリは明らかに

List(
(User(Some(1),"User1Name"),Item(Some(1),Some(1),"Item Description 1")), 
(User(Some(1),"User1Name"),Item(Some(2),Some(1),"Item Description 2"))) 

は、ユーザーケースクラスに「多くの」部分を引くエレガントな方法があります...与えたユーザに属する各「アイテム」の「ユーザー」のレコードを複製しますか?それがスリックかスカラかどうか。私が理想的になるのは理想的です...

User(Some(1),"User1Name", 
    List(Item(Some(1),Some(1),"Item Description 1"), 
     Item(Some(2),Some(1),"Item Description 2"))) 

ありがとう! Scalaでそれを行うには

答えて

1

一つの方法:

val results = List((User(Some(1), "User1Name"), Item(Some(1), Some(1), "Item Description 1")), 
        (User(Some(1), "User1Name"), Item(Some(2), Some(1), "Item Description 2"))) 

val grouped = results.groupBy(_._1) 
        .map { case (user, item: List[(User, Item)]) => 
         user.copy(items = Option(item.map(_._2))) } 

これは、複数の異なるUser S(groupedIterable[User]である)を扱います。

関連する問題