使用PlayFramework的JSON中的父子关系

时间:2014-09-25 04:14:19

标签: json scala playframework-2.0 slick

我需要为我的Angular JS应用程序提供一个JSON,它表示表的父子关系。 父(集团):

+----+---------------+-------------+----------------+
| id | external_code | supplier_id | notes          |
+----+---------------+-------------+----------------+
| 19 | asdfas        |           3 | sadfa          |
| 23 | 454           |           1 | groupa1        |
| 24 | sadfas221     |           2 | asfd           |
| 25 | dsafas        |           2 | NULL           |
| 21 | 4545          |           1 | asdfasf        |
+----+---------------+-------------+----------------+

子(GroupItems):

+----------+---------+--------+
| group_id | item_id | status |
+----------+---------+--------+
|       19 |       1 |      0 |
|       19 |       2 |      0 |
|       19 |       3 |      0 |
|       25 |       2 |      0 |
+----------+---------+--------+

我想要的JSON应该是这样的:

[
{"groupId":"19",
"notes":"sadfa",
"extenalCode":"asdfas",
"supplierId":"2",
"itemCount":3
"items":[{"itemId": "1","status":"Created", "weight":23},
         {"itemId": "2","status":"Created", "weight":23}
         {"itemId": "3","status":"Created", "weight":23}
        ]

},

....

]

问题是如何使用MySQL和PlayFramework2.0(Slick)插入和绑定表示JSON语义的父项的子项?

1 个答案:

答案 0 :(得分:0)

大致是这样的:

val items =
  GroupItems.join(Items).on(_.itemId === _.id).run // <- query fetching items with group_ids
            .groupBy(_._1.groupId).toMap
            .mapValues(_._2) // <- mapping Map values to only items

// render groups to json and add a field items with the items (I may be wrong about Play's json api names)
val json = Group.run.map(g => Json.toJson(g) ++ JsObject("items" -> Json.toJson(items(g.id))))