请帮我找到 ActiveRecord 的
:source
关联的 has_one/has_many :through
选项的 Elixir/ecto 选项。
这是我的问题,我有以下模式:
User
,Event
,AttendingEvents
。一个User
有很多事件,一个Event
属于一个用户。然后是AttendedEvents
,它既属于用户又属于组。所以,在 Rails 中我会这样做:
class User < ApplicationRecord
has_many :attending_events, dependent: :destroy
has_many :attended_events, through: :attending_events, source: :event, foreign_key: :attendee_id
end
class Event < ApplicationRecord
has_many :attending_events
has_many :attendees, through: :attending_events, source: :user
end
既然 ecto 没有
source
,我该如何重写它,以便我能够做到这一点而不是查询?
event = MyApp.Repo.get(MyApp.Event, id) |> MyApp.Repo.preload(:attendees)
event.attendees
如果我理解你的架构和要求,你可以这样做。
defmodule MyApp.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
# User schema fields
has_many :attending_events, MyApp.AttendingEvent
has_many :attended_events, through: [:attending_events, :event]
end
end
defmodule MyApp.Event do
use Ecto.Schema
import Ecto.Changeset
schema "events" do
# Event schema fields
has_many :attending_events, MyApp.AttendingEvent
has_many :attendees, through: [:attending_events, :user]
end
end
defmodule MyApp.AttendingEvent do
use Ecto.Schema
import Ecto.Changeset
schema "attending_events" do
belongs_to :user, MyApp.User
belongs_to :event, MyApp.Event
end
end
有了这些模式和映射,您的查询就变成了:
event =
MyApp.Repo.get(MyApp.Event, id)
|> MyApp.Repo.preload(attendees: MyApp.User)
有道理吗?