Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Group By clause in preload

Tags:

elixir

ecto

I have a model that has a many to many association through a HABTM join table. However, my join table does not uniquely map my row, hence I need to add a group_by clause to get my unique rows.

Is there a way to add a group by expression when using Repo.preload?

Repo.get!(P1, p1_id)
|> Repo.preload(:c0)

Generated query:

SELECT 
    c0.*, p1."id" FROM "c0" AS c0
LEFT JOIN "p1" AS p1
    ON p1."id" = 2
LEFT  JOIN "c2" AS c2
    ON c2."p1" = p1."id"
WHERE (c2."c1_id" = c0."id")

Target query:

SELECT 
    c0.*, p1."id" FROM "c0" AS c0
LEFT JOIN "p1" AS p1
    ON p1."id" = 2
LEFT  JOIN "c2" AS c2
    ON c2."p1" = p1."id"
WHERE (c2."c1_id" = c0."id")
GROUP BY c0."id", p1."id"
like image 230
Secret Avatar asked Aug 30 '26 20:08

Secret


1 Answers

New to this, I haven't tested on local but I think it is achievable as following;

query = from p in P1,
        join: c in assoc(p, :c0)
        group_by: p.id
        preload: [c0: c]
Repo.get(query, p1_id)
like image 83
smlnl Avatar answered Sep 06 '26 21:09

smlnl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!