【发布时间】:2017-02-09 13:17:25
【问题描述】:
我有两个models、Person和Pet,我想要一个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