2017-02-09 101 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 

這將確保字段不爲空(並不總是必要的),並且它不」不會破壞參照完整性。