我有以下数据库表关系。
Prefecture
1-1 Member
1-NMemberAction
如果要使用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)
请给我一些建议。
谢谢。
您如何定义架构?确保它们类似于以下内容:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句