gpt4 book ai didi

elixir - 基于 Ecto 关联查询

转载 作者:行者123 更新时间:2023-12-04 14:25:54 26 4
gpt4 key购买 nike

在 Rails Controller 中,您经常会看到以下代码,以便仅获取属于 current_user 的帖子;

class PostsController < APIController
def show
current_user.posts.find(params[:id])
end
end

用 Ecto 表达这一点的最佳方式是什么?

最佳答案

您可以使用 Ecto.Model.assoc/2连同 repo 功能。

获取单个元素:

assoc(current_user, :posts) |> Repo.get(id)

要获取用户的所有帖子:
assoc(current_user, :posts) |> Repo.all()

您还可以使用它来编写查询:

例如
defmodule Post do
use Ecto.Model

...

def published(query) do
from p in query,
where: p.published
end
end

assoc(current_user, :posts) |> Post.published() |> Repo.all()

关于elixir - 基于 Ecto 关联查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33309883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com