Elixir Ecto:如何使用belongs_to和has_many编写迁移?

Mar*_*iro 9 postgresql elixir ecto phoenix-framework

我有两个型号,Person并且Pet,我希望Person能够有很多宠物,但Pet属于只有一个人:

defmodule MyApp.Person do
  use MyApp.Web, :model

  alias MyApp.Pet

  schema "persons" do
    field :name, :string
    has_many :pets, Pet
    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end
Run Code Online (Sandbox Code Playgroud)

defmodule MyApp.Pet do
  use MyApp.Web, :model

  alias MyApp.Person

  schema "pets" do
    field :name, :string
    belongs_to :person, Person
    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end
Run Code Online (Sandbox Code Playgroud)

那么,我该如何编写迁移呢?

defmodule Iloveproblems.Repo.Migrations.CreatePersonsAndPets do
  use Ecto.Migration

  def change do
    create table(:persons) do
      add :name, :string
      # I don't know :( . The has_many stuff
      timestamps()
    end

    create table(:pets) do
      add :name, :string
      # I don't know :( . The belongs_to stuff
      timestamps()
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我正在使用Postgres.

提前致谢!

NoD*_*ame 11

我想我会在这里发表评论.

为了创建用作外键的字段,您可以编写如下内容:

add :person_id, references(:persons), null: false
Run Code Online (Sandbox Code Playgroud)

这可确保该字段不为空(并非总是必需),并且不会破坏参照完整性.