如何使用嵌套关系编写 ecto 代码

How to write ecto code with nested relation

我有以下数据库 table 关系。

Prefecture 1 - 1 Member 1 - N MemberAction

我想获取数据,以防SQL。

    SELECT A.action, M.member_name, 
      FROM MemberAction A
      JOIN Member M 
        ON M.id = A.member_id
      JOIN Prefecture P
        ON M.prefecture_id = P.id

但是我不知道用Ecto写代码。 以下代码不起作用。因为 MemberAction does not have association

    query = from a in MemberAction,
            where: a.id == ^action_id,
            preload: [:member, :prefecture]
    Repo.all(query)

请多多指教

谢谢。

使用Ecto.Query.join/5.

query = from a in MemberAction,
  join: m in Member,
  on: [id: a.member_id]
  join: p in Prefecture,
  on: [id: m.prefecture_id],
  select: {a.action, m.member_name}

您是如何定义架构的?确保它们类似于以下内容:

defmodule YourApp.Schema.Prefecture do
  use Ecto.Schema
  schema "prefectures" do
    # your fields
  
    has_one(:member)
  end
end

defmodule YourApp.Schema.Member do
  use Ecto.Schema
  schema "members" do
    # your fields
  
    belongs_to(:prefecture)
    has_many(:member_actions)
  end
end

defmodule YourApp.Schema.MemberAction do
  use Ecto.Schema
  schema "member_actions" do
    # your fields
  
    belongs_to(:member)
  end
end

然后您应该能够使用与您的非常相似的查询

    query = from a in MemberAction,
            where: a.id == ^action_id,
            preload: [member: :prefecture]
    Repo.all(query)