2
我有兩個models,Person
和Pet
,我想一個Person
能夠have many寵物,但Pet
到belong 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
我正在使用。
在此先感謝!
'add:person_id,references(:persons),null:false'等作爲一種方式。 – JustMichael