如何格式化ecto join查询的json响应?

问题描述 投票:0回答:1

我想用特定的json格式化来自ecto查询的join查询结果。这是我的ecto查询的片段。

    query = from(ms in Group,
     join: m in Users,
     on: ms.id == m.group_id,
     select: %{group_id: ms.id, group_name: ms.name, updated_at: 
               ms.updated_at, user_name: m.name, 
               description: m.description},
     where: ms.id == ^group_id
   )
  result =
    query
    |> order_by(desc: :created_at)
    |> Repo.all()
    |> Enum.map(
      &Map.take(&1, [
        :group_id,
        :group_name,
        :updated_at,
        :user_name,
        :description
      ])
    )

而当前的输出响应是:

{
  "success": true,
  "data": [
    {
      "updated_at": "2019-12-21T12:04:11Z",
      "user_name": "Adam",
      "group_name": "Premium",
      "description": "Romantic Man",
      "group_id": "P001"
    },
    {
      "updated_at": "2019-12-21T12:04:11Z",
      "user_name": "Antony",
      "group_name": "Premium",
      "description": "Strong Man",
      "group_id": "P001"
    }
  ]
}

当前的响应包含了多余的数据,来自于 Group 数据库的预期输出是。

{
  "success": true,
  "data": {
    "group_id": "P001",
    "group_name": "Premium",
    "updated_at": "2019-12-21T12:04:11Z",
    "users": [
      {
        "user_name": "Adam",
        "description": "Romantic Man"
      },
      {
        "user_name": "Antony",
        "description": "Strong Man"
      }
   }
}

如何实现?

elixir ecto
1个回答
0
投票

在查询中尝试group_by,你可能需要一个数组聚合器来获得你想要的用户。 我想你需要使用一个片段来让数组这块工作。


0
投票

试着替换

|> Enum.map(
  &Map.take(&1, [
  .....

有以下片段

|> Enum.group_by(query, & &1.group_id) 
|> Enum.map(fn {_group_id, users} ->

  user_details = Enum.map(users, &Map.take(&1, ~w(user_name description)a))

  hd(users) 
  |> Map.drop(~w(user_name description)a) 
  |> Map.put(:users, user_details)
end)
© www.soinside.com 2019 - 2024. All rights reserved.