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

Elixir Ecto: How to write a migration with belongs_to and has_many?

我有两个models, Personand Pet, and I want a Personto be able to have many pets, but a Petto belong to只有一个人:

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

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

那么,我该如何写 migration 呢?

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

我正在使用 Postgres

提前致谢!

我想我会把我的评论移到这里。

为了创建一个用作外键的字段,你可以这样写:

add :person_id, references(:persons), null: false

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