【问题标题】:Ecto inserting in-between recordEcto 插入中间记录
【发布时间】:2015-12-09 04:50:34
【问题描述】:

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

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

我创建了以下结构:

表 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

表2,用户数据:

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

在中间的表格中保存用户在事件中的存在情况:

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

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    以下架构定义应该完成您想要做的事情(从您提供的架构中简化):

    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!
    

    【讨论】:

    • 非常感谢您的快速回复,我会尽快查看。
    • 我在尝试插入模型时不断收到“约束错误:* foreign_key:presents_user_id_fkey 如果您想将此约束转换为错误,请在您的变更集中调用 foreign_key_constraint/3 并定义正确的约束名称. 变更集没有定义任何约束。”所以我调用了编辑的变更集方法。 (已编辑主帖的底部)在代码中我调用了您编写的确切代码(仅用于测试目的)
    • 现在工作了吗? :user_id:event_idUserEvent 记录需要已经存在才能针对外键约束进行验证。
    • 现在它正在工作,我忘记了我不知道用户 1... 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多