我在n-n
和posts
表之间有2个tags
关系。这是我在Postgres中的查询:
SELECT t0.*, array_to_string(array_agg(t2.tag), ', ')
FROM "posts" AS t0
INNER JOIN "posts_tags" AS t1 ON (t0.id = t1.post_id)
INNER JOIN "tags" AS t2 ON (t1.tag_id = t2.id)
GROUP BY t0.id
我尝试在Ecto
中使用类似的内容:
Repo.all(
from p in Post,
join: a in Post_Tag, on: p.id == a.post_id,
join: t in Tag, on: a.tag_id == t.id,
select: {p, array_to_string(array_agg(t.tag),', ')},
limit: ^limit,
offset: ^offset,
group_by: p.id
)
但是我得到这个错误:
(Ecto.Query.CompileError) `array_to_string(array_agg(t.tag()), ', ')` is not a valid query expression.
答案 0 :(得分:2)
对于查询的array_to_string(...)
部分,您需要使用fragment/1。我还没有测试过,但是看起来应该像这样:
fragment("array_to_string(array_agg(?), ', ')", t.tag)