Ecto:当表的主键是关联的id时怎么办

时间:2016-04-22 10:13:40

标签: elixir phoenix-framework ecto

我正在为freeradius-mysql开发REST API(所以我不管理数据库......) Freeradius有这个奇怪的架构:

" group"表:

schema "radusergroup" do
  field :username, :string, primary_key: true
  field :priority, :integer
  field :groupname, :string
end

"用户"表:

schema "userinfo" do
 field :username, :string 
 field :firstname, :string
 field :lastname, :string
 field :email, :string
 .
 .
 .
 field :creationdate, :datetime
 field :creationby, :string
 field :updatedate, :datetime
 field :updateby, :string
 field :username, :string
 has_one :group, Rascal.Group, references: :username,
   foreign_key: :username, on_delete: :delete_all
end

我的问题是我想这样做:

schema "radusergroup" do
  belongs_to :user, Rascal.User, foreign_key: :username, references: :username, type: :string, primary_key: true
  field :priority, :integer
  field :groupname, :string
end

但是Ecto不允许这样做。 有什么好主意的吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

我试图实现你需要的结构。

迁移

用户:

defmodule ExampleApp.Repo.Migrations.CreateUser do
  use Ecto.Migration

  def change do
    create table(:userinfo, primary_key: false) do
      add :username, :string, primary_key: true # note the primary_key

      timestamps
    end
    create unique_index(:userinfo, [:username])


  end
end

组:

defmodule ExampleApp.Repo.Migrations.CreateGroup do
  use Ecto.Migration

  def change do
    create table(:radusergroup) do

      add :username, references(:userinfo, on_delete: :nothing, column: :username, type: :string)

      add :priority, :integer
      add :groupname, :string

      timestamps
    end
    create index(:radusergroup, [:username])

  end
end

模型

用户:

defmodule ExampleApp.User do
  use ExampleApp.Web, :model

  @primary_key {:username, :string, autogenerate: false}
  schema "userinfo" do
    has_one :group, ExampleApp.Group, foreign_key: :username, on_delete: :delete_all

    timestamps
  end

  @required_fields ~w()
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

组:

defmodule ExampleApp.Group do
  use ExampleApp.Web, :model

  schema "radusergroup" do
    belongs_to :username, ExampleApp.Username, references: :username, type: :string

    field :priority, :integer
    field :groupname, :string

    timestamps
  end

  @required_fields ~w()
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

是否满足您的需求?