Ecto 插入中间记录

Ecto inserting in-between record

我对 Phoenix、Ecto 生态系统还很陌生。我正在尝试在 table 之间创建用于处理多对多关系。不幸的是,我不知道如何创建变更集(插入它)来保存用户和事件数据,而且我很难在可用资源中找到该信息。你能帮忙吗?至少我指出了正确的方向?

当我在执行另一项关系任务时,我使用的是 build/2,但它只需要一个关联参数。

我创建了以下结构:

Table 1、带事件的数据:

schema "events" do
    field :name, :string
    field :address, :string

    field :location_x, :float
    field :location_y, :float

    field :date, Ecto.DateTime

    field :description, :string

    has_many :presences, Kpsz.Model.Presence
  end

Table2、数据与用户:

schema "users" do
    field :login, :string
    field :password, :string
    field :email, :string

    field :role, :integer

    field :name, :string
    field :surname, :string
    field :class, :string
    field :phone_number, :string
    field :avatar, :string

    has_many :presences, Kpsz.Model.Presence

    timestamps
  end

并且在此期间 table 保持用户出席活动:

schema "presences" do
    belongs_to :user, Kpsz.Model.User, foreign_key: :user_id
    belongs_to :event, Kpsz.Model.Event, foreign_key: :event_id
  end

def changeset(user, params \ :empty) do
    user
      |> cast(params, @required_fields, @optional_fields)
      |> foreign_key_constraint(:user_id)
      |> foreign_key_constraint(:event_id)
  end

以下架构定义应该可以完成您想要执行的操作(根据您提供的架构进行了简化):

defmodule Event do
  use Ecto.Model
  schema "events" do
    has_many :presences, Presence
    has_many :users, through: [:presences, :user]
  end
end

defmodule User do
  use Ecto.Model
  schema "users" do
    has_many :presences, Presence
    has_many :events, through: [:presences, :event]
  end
end

defmodule Presence do
  use Ecto.Model
  schema "presences" do
    belongs_to :user, User
    belongs_to :event, Event
  end
end

有关详细信息,请参阅带有 :through 选项的 Ecto.Schema.has_many/3 的文档。

预加载:through关联也会预加载连接的关联,例如:

iex> event = Event |> Repo.get!(1) |> Repo.preload([:users])
iex> # at this point, both event.presences and event.users have been loaded

插入一条Presence记录也可以直接完成:

iex> presence = %Presence{ user_id: 1, event_id: 1 } |> Repo.insert!