Ecto Postgresql查询,返回返回的每个产品的类别列表

时间:2018-06-04 09:28:50

标签: postgresql elixir ecto

我有一个查询,从数据库和他们所在的商店中选择产品。每个产品都有一个或多个类别,位于一个或多个商店。

查询:

def create_unique_shop_query_no_keyword(categories, shop_ids) do
    products_shops_categories = from p in Product,
    join: ps in ProductShop, on: p.id == ps.p_id,
    join: s in Shop, on: s.id == ps.s_id,
    join: pc in ProductCategory, on: p.id == pc.p_id,
    join: c in Subcategory, on: c.id == pc.c_id,
    distinct: s.id,
    where: c.id in ^categories,
    where: s.id in ^shop_ids,
    group_by: [s.id, s.name],
    select: %{products: fragment(
      "json_agg( DISTINCT (?, ?, ?, ?, ?, ?, ?, ?, ?)) AS products", 
      p.id, 
      p.name, 
      p.brand, 
      p.description, 
      p.image, 
      p.rating, 
      p.number_of_votes, 
      ps.not_in_shop_count, 
      ps.price),
      shop: fragment(
        "json_agg( DISTINCT (?, ?, ST_X(?), ST_Y(?))) AS shop", 
        s.id, 
        s.name, 
        s.point, 
        s.point
        )
      }
  end

我想将产品的类别添加到查询结果中。我想将这些类别列为产品中的列表。

当我这样做时:

    ...select: %{products: fragment(
      "json_agg( DISTINCT (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) AS products", 
      p.id, 
      p.name, 
      p.brand, 
      p.description, 
      p.image, 
      p.rating, 
      p.number_of_votes, 
      ps.not_in_shop_count, 
      ps.price,
      c.id,
      c.name),...

它会在每个类别的结果中重复产品。

我可以在查询中添加这样的内容:

categories: fragment(
    "json_agg( DISTINCT (?, ?, ?, ?, ?)) AS categories", 
    pc.id,
    c.id,
    p.name,
    c.name,
    p.id
    ),

我得到的这个列表包含产品,产品类别和类别的ID。尽管如此,这并不是很好:

enter image description here

最好只将类别列表添加到返回的产品中。如何为结果中返回的每个产品添加类别列表(c.id和c.name)?

0 个答案:

没有答案