在特定日期发布comments
的特定user
posts
获取所有post
的最佳方法是什么? ?
即。 some_user.posts.comments where post.published_on == '2016-01-01'
我没有兴趣将帖子作为中间步骤,只是评论。
答案 0 :(得分:0)
您需要join
使用assoc(post, :comments)
,然后select
仅注释:
from(p in Post,
where: p.user_id == ^user.id and p.inserted_at == ^"2016-10-12T08:30:34Z",
join: c in assoc(p, :comments),
select: c)
iex(1)> user = Repo.get!(User, 1)
iex(2)> Repo.all from(p in Post, where: p.user_id == ^user.id and p.inserted_at == ^"2016-10-12T08:30:34Z", join: c in assoc(p, :comments), select: c)
[debug] QUERY OK source="posts" db=0.6ms
SELECT c1."id", c1."content", c1."post_id", c1."user_id", c1."inserted_at", c1."updated_at" FROM "posts" AS p0 INNER JOIN "comments" AS c1 ON c1."post_id" = p0."id" WHERE ((p0."user_id" = $1) AND (p0."inserted_at" = $2)) [1, {{2016, 10, 12}, {8, 30, 34, 0}}]
[%MyApp.Comment{__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
content: nil, id: 1, inserted_at: #Ecto.DateTime<2016-10-12 08:30:42>,
post: #Ecto.Association.NotLoaded<association :post is not loaded>,
post_id: 1, updated_at: #Ecto.DateTime<2016-10-12 08:30:42>,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 1},
%MyApp.Comment{__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
content: nil, id: 2, inserted_at: #Ecto.DateTime<2016-10-12 08:39:41>,
post: #Ecto.Association.NotLoaded<association :post is not loaded>,
post_id: 1, updated_at: #Ecto.DateTime<2016-10-12 08:39:41>,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 1},
%MyApp.Comment{__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
content: nil, id: 3, inserted_at: #Ecto.DateTime<2016-10-12 08:39:42>,
post: #Ecto.Association.NotLoaded<association :post is not loaded>,
post_id: 1, updated_at: #Ecto.DateTime<2016-10-12 08:39:42>,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 1}]
上面的我的应用没有published_on : Ecto.Date
所以我使用了inserted_at : Ecto.DateTime
。只需将inserted_at
更改为published_on
,然后将值更改为可以通过ecto强制转换为Ecto.Date
的有效类型,它应该适用于您的应用。