更新没有模型的链接表(Phoenix)

时间:2017-10-06 06:24:35

标签: elixir phoenix-framework ecto

我有一个简单的多对多关系,我希望能够轻松更新。

我创建了两个具有主表的模式,并由没有模式的链接表连接。

迁移

defmodule MyApp.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :name, :string
      timestamps()
    end
  end

  def change do
    create table(:organizations) do
      add :orgname, :string
      timestamps()
    end
  end

  def change do
    create table(:users_organizations, primary_key: false) do
      add :user_id, references(:users), null: false
      add :organization_id, references(:organizations), null: false
      timestamps()
    end
    create index(:users_organizations, [:user_id])
    create index(:users_organizations, [:organization_id])
    create index(:users_organizations, [:user_id, :organization_id], unique: true)
  end
end

模型

  schema "users" do
    field :name, :string
    many_to_many :organizations, MyApp.Accounts.Organization, join_through: "users_organizations"
    timestamps()
  end

  schema "organizations" do
    field :orgname, :string
    many_to_many :users, MyApp.Accounts.User, join_through: "users_organizations"
    timestamps()
  end

种子

alias MyApp.Repo
alias MyApp.Accounts.User
alias MyApp.Accounts.Organization

Repo.insert!(%User{ name: "Aaron"} )
Repo.insert!(%User{ name: "Bob"} )
Repo.insert!(%User{ name: "Calvin"} )

Repo.insert!(%Organization{ orgname: "Airport"} )
Repo.insert!(%Organization{ orgname: "Brokerage"} )
Repo.insert!(%Organization{ orgname: "College"} )

如果不采用原始查询,是否可以编写将Aaron和Bob添加到机场的ecto命令,然后在此场景中将Bob从机场中删除?这需要在不使用users_organizations等架构的情况下将记录插入表MyApp.Accounts.UsersOrganizations

如果没有,是否始终建议架构伴随链接表?

0 个答案:

没有答案