foreign_key :country_id 必须与相应的关联名称不同

foreign_key :country_id must be distinct from corresponding association name

当我运行 mix ecto.migrate遇到错误,(ArgumentError) foreign_key :country_id must be distinct from corresponding association name lib/ecto/schema.ex:1499: Ecto.Schema.__belongs_to__/4

我的目标是在我的手机 table 中添加两个外键,即 conutry_id 和 country_code。我缺少什么?

这是我的手机架构:

schema "mobiles" do
field :number, :string

belongs_to :person, Person.Person
belongs_to :country_id, Person.Country, foreign_key: :country_id
belongs_to :country_code, Person.Country, foreign_key: :country_code
has_many :mobile_audits, Person.MobileAudit, on_delete: :delete_all

timestamps()
end

这是我的国家模式:

schema "countries" do
field :code, :string
field :name, :string
field :iso_codes, :string

has_many :mobiles, Person.Mobile, on_delete: :delete_all

timestamps()
end

这是我的迁移脚本:

def change do
alter table(:mobiles) do
  add :country_id, references(:countries, type: :binary_id, column: :id)
  add :country_code, references(:countries, type: :string, column: :code)
end
end

非常感谢!

belongs_to :country_id, Person.Country, foreign_key: :country_id

这个宏调用的形式是belongs_to :name, QueryAbleModuleName, opts。现在在您的例子中, :name 参数和 foreign_key 选项具有相同的值。一般来说,foreign_key 应该是 <name>_id

如果 table 有 company_id 字段,那么调用应该如下所示:

belongs_to :company, MyModule.Company, foreign_key: :company_id

因此,如果您希望 country_idcountry_code 作为关联名称,请考虑将外键设置为 country_id_idcountry_code_id,并确保您的数据库模式反映了这一点。

或者考虑一些在您的上下文中更有意义的事情。