【问题标题】:Elixir Ecto: How to write a migration with belongs_to and has_many?Elixir Ecto:如何使用 belongs_to 和 has_many 编写迁移?
【发布时间】:2017-02-09 13:17:25
【问题描述】:

我有两个modelsPersonPet,我想要一个Person能够have many宠物,但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 等等作为一种方法。

标签: postgresql elixir phoenix-framework ecto


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多