1
我有模式,看起来如下:构建HAS_ONE关系
defmodule Busiket.LanguageCode do
use Busiket.Web, :model
schema "languages_code" do
field :code, :string
field :text, :string
timestamps
end
end
第二个模式:
defmodule Busiket.CountryCode do
use Busiket.Web, :model
schema "countries_code" do
field :alpha2, :string
field :alpha3, :string
timestamps
end
end
和第三台
defmodule Busiket.Country do
use Busiket.Web, :model
alias Busiket.LanguageCode
alias Busiket.CountryCode
schema "countries" do
has_one :code, CountryCode
has_one :lang, LanguageCode
field :text, :string
timestamps
end
end
,你可以在看第三个模式,字段code
应取决于country_code
模式与字段code
。
lang字段应取决于language_code
架构与字段alpha2
。
我不知道,如果架构国家是精心设计的?
在国家中的条目应该是这样的:
"CH" | "EN" | "Switzerland"
"DE" | "EN" | "Germany"
这个记录应zhcon失败:
"YY" | "EN" | "Foo"
因为没有与YY
ISO代码的国家。
从language_code
迁移文件看起来如下:
defmodule Busiket.Repo.Migrations.CreateLanguageCode do
use Ecto.Migration
def change do
create table(:languages_code) do
add :code, :string, size: 3
add :text, :string
timestamps
end
end
end
和country_code
defmodule Busiket.Repo.Migrations.CreateCountryCode do
use Ecto.Migration
def change do
create table(:countries_code) do
add :alpha2, :string, size: 2
add :alpha3, :string, size: 3
timestamps
end
end
end
,最后我试着用country
迁移:
defmodule Busiket.Repo.Migrations.CreateCountryTable do
use Ecto.Migration
def change do
create table(:countries) do
add :code, references(:countries_code), [name: :alpha2]
add :lang, references(:languages_code), [name: :code]
add :text, :string
timestamps
create unique_index(:countries, [:code, :lang])
end
end
end
我希望,它是清楚我想要达到的目标。
UPDATE
我创建的表为你伤心:
defmodule Busiket.Repo.Migrations.CreateCountryTable do
use Ecto.Migration
def change do
create table(:countries) do
add :coun, references(:countries_code, column: :alpha2, type: :string)
add :lang, references(:languages_code, column: :code, type: :string)
add :text, :string
timestamps
end
create unique_index(:countries, [:coun, :lang])
end
end
当我执行混合ecto.migrate,我有以下错误:
20:34:11.012 [info] create table countries
** (Postgrex.Error) ERROR (invalid_foreign_key): there is no unique constraint matching given keys for referenced table "countries_code"
我想,我必须改变:alpha3不是唯一的。
如何HAS_ONE在'CountryCode'和'LanguageCode'模式应该样子? –
我更新了我的帖子。 –
我想你还需要在'countries_code'中为'alpha2'添加一个唯一索引,并在'languages_code'中为'code'添加一个唯一索引。如果您编辑现有迁移以添加这些字段,请务必重新运行迁移。 – Dogbert