我有一系列复杂的查询,我使用Ecto在Elixir / Phoenix中运行。这些目标是使这些查询适用于创建新条目和更新以前的行。为此,我设想使用一个函数参数来定义我们是否正在更新表。例如,现在我有以下功能:
@login_required
def contactformview(request):
form = ContactForms(request.POST or None)
if form.is_valid():
form.save()
return HttpResponse(' Thanks For Contacting WIth Us We Will Get Back To You Within 24 Hours')
return render(request, 'contact-us.html', {'form':form})
我想更改功能,以便它如下:
# Retrieves the stats on the user chargebacks
defp get_chargebacks(%{user_id: user_id} = map) do
query =
from u in Users,
left_join: c in ChargeBacks, on: [user_id: u.id],
where: u.id == ^user_id,
select: %{chargeback_amount_cents: sum(c.amount), chargeback_amount_count: count(c.user_id), chargeback_amount_currency: @default_currency},
group_by: u.id
result = query
|> RepoBVCore.one
Map.merge(map, Map.put(result, :chargeback_amount_cents, Map.get(result, :chargeback_amount_cents) || 0))
end
如果defp get_chargebacks(%{user_id: user_id} = map, is_update \\ false)
那么我想在函数中添加一个is_update = true
子句(例如):
where
如何更改原始函数以有条件地更改查询语句?感谢。
答案 0 :(得分:4)
您可以通过将2个名称的列表作为绑定传递给c
来访问Ecto.Query.where/3
。 c
将是该列表中的第二个项目,因为它是原始查询中的第一个join
(源表是第一个,连接在它之后按照它们在原始连接中的顺序连接查询):
defp get_chargebacks(%{user_id: user_id} = map, is_update \\ false) do
query =
from u in Users,
left_join: c in ChargeBacks, on: [user_id: u.id],
where: u.id == ^user_id,
select: %{chargeback_amount_cents: sum(c.amount), chargeback_amount_count: count(c.user_id), chargeback_amount_currency: @default_currency},
group_by: u.id
query =
if is_update do
query |> where([u, c], c.amount > 100)
else
query
end
...