【问题标题】:modify ecto many_to_many schema修改 ecto many_to_many 模式
【发布时间】:2018-09-13 21:33:45
【问题描述】:

有这个架构

many_to_many :customers, User,
  join_through: Customer, on_replace: :delete

我想添加一个 on_delete 子句:

on_delete: :delete_all

所以我用

修改了架构
many_to_many :customers, User,
  join_through: Customer, on_replace: :delete,
  on_delete: :delete_all

并创建了一个迁移,但由于它是多对多的,并且它创建了一个新表,我不知道如何引用该字段,我已经搜索了 ecto 文档,但找不到涵盖这种情况的示例:

defmodule Migration do
  use Ecto.Migration

  def change do
    alter table(:products) do
      modify :customers, references(:customers, on_delete: :delete_all)
    end
  end
end

但是在运行迁移时,它显然告诉我列客户不存在:

(undefined_column):关系“产品”的“客户”列不 存在

在 iex 上显示为 ecto 关联

customers: #Ecto.Association...

总结一下,基本上,我想在删除产品的时候删除客户。

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    对于多对多关系,必须使用连接表。 例如,一个用户可能有许多角色,而一个角色可能属于许多用户......

    schema "users" do
      field(:username, :string)
      many_to_many(:roles, Role, join_through: UserRole, on_replace: :delete, on_delete: :delete_all)
    
    schema "users_roles" do
      belongs_to(:user, User)
      belongs_to(:role, Role)
    
    schema "roles" do
      field(:name, :string)
      # optional - if you need to use the relationship in the "reverse" direction.
      # many_to_many(:users, User, join_through: UserRole)
    

    Documentation for many_to_many options

    表中的外键对应schema中的belongs_to

    create table(:users, primary_key: false) do
      add :id, primary_key: true
      add :username, :string, null: false
    end
    
    create table(:users_roles, primary_key: false) do
      add :user_id, references(:users, on_delete: :delete_all), null: false
      add :role_id, references(:roles, on_delete: :delete_all), null: false
    end
    
    create table(:roles, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :name, :string, null: false
    end
    

    Documentation for references options

    【讨论】:

    • 嗨,我有使用连接表创建的架构,但我缺少 many_to_many 上的 on_delete: :delete_all,我的问题是如何将该子句添加到迁移中?我正在尝试修改:customers,references(:customers, on_delete: :delete_all)
    • 您好,我想您可能正在尝试更新错误的表。这有点违反直觉,但是尽管(在您的情况下) many_to_many 存在于“产品”模式中。外键存在于连接表上。我试图在我的示例中说明这一点。
    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多