You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化查询图片接口中product_id的空值判断逻辑?

简化Elixir/Ecto中product_id空值检查逻辑

你可以通过Ecto查询的动态组合特性去掉冗余的case分支,让代码更紧凑线性,同时保留原有功能:

def list_pictures(attr \\ params) do
  product_id = Map.get(attr, "product_id")

  Picture
  |> then(fn base_query ->
    if product_id do
      # 当product_id存在时,通过关联表过滤图片ID
      product_picture_ids = from(pp in Mirror.Imports.ProductPicture,
        where: pp.product_id == ^product_id,
        select: pp.picture_id
      )
      from(p in base_query, where: p.id in subquery(product_picture_ids))
    else
      # product_id为空时直接返回基础查询(所有图片)
      base_query
    end
  end)
  |> preload(:product)
  |> Repo.all()
end

或者用Ecto.Query.dynamic进一步简化条件拼接:

def list_pictures(attr \\ params) do
  product_id = Map.get(attr, "product_id")

  filter_condition = 
    if product_id do
      product_picture_ids = from(pp in Mirror.Imports.ProductPicture,
        where: pp.product_id == ^product_id,
        select: pp.picture_id
      )
      dynamic([p], p.id in subquery(product_picture_ids))
    else
      # 空条件,匹配所有数据
      dynamic(true)
    end

  from(p in Picture, where: ^filter_condition)
  |> preload(:product)
  |> Repo.all()
end

这两种写法都去掉了原代码中的case分支,逻辑更连贯:

  • 当product_id不为空时,动态添加关联表的过滤条件
  • 当product_id为空时,直接查询所有Picture数据

代码结构更简洁,也符合Ecto查询的组合式编程风格。

内容的提问来源于stack exchange,提问作者Chen Yu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:45:35