2017-02-09 100 views
2

我有两个modelsPersonPet,我想一个Person能够have many宠物,但Petbelong to只有一个人:Elixir Ecto:如何使用belongs_to和has_many编写迁移?

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 

我正在使用。

在此先感谢!

+2

'add:person_id,references(:persons),null:false'等作为一种方式。 – JustMichael

回答

2

我想我会在这里发表我的评论。

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

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

这将确保字段不为空(并不总是必要的),并且它不”不会破坏参照完整性。