【问题标题】:Parent-Child Relationship in JSON using PlayFramework使用 PlayFramework 的 JSON 中的父子关系
【发布时间】:2014-11-19 17:49:36
【问题描述】:

我需要为我的 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 语义的父项的子项?

【问题讨论】:

  • 将嵌套文档序列映射为多个文档序列,每个嵌套层一个并添加父 ID。然后使用 insertAll 来插入这些序列中的每一个的顶级项?
  • @cvogt 你能详细说明一下吗?我对 scala 和 slick API 真的很陌生。
  • 误读了你的问题,你问的不是数据库插入,对吧?

标签: json scala playframework-2.0 slick


【解决方案1】:

大概是这样的:

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))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多