Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 简单外键_Elixir_Phoenix Framework - Fatal编程技术网

Elixir 简单外键

Elixir 简单外键,elixir,phoenix-framework,Elixir,Phoenix Framework,在我的Phoenix应用程序中,我有一个联系人表和一个地址表。联系人模式为: schema "contacts" do field :name, :string field :number, :string has_one :address, App.Address, on_delete: :nothing timestamps() end 地址模式为 schema "addresses" do field :name, :string fie

在我的Phoenix应用程序中,我有一个联系人表和一个地址表。联系人模式为:

schema "contacts" do
    field :name, :string
    field :number, :string
    has_one :address, App.Address, on_delete: :nothing

    timestamps()
end
地址模式为

schema "addresses" do
    field :name, :string
    field :lat, :decimal
    field :lng, :decimal

    timestamps()
end
我只想通过数据库中填写的地址下拉列表选择联系人中的地址。然而,凤凰城正在回归

`App.Address.contact_id` in `where` does not exist in the schema in query:

from a in App.Address,
  where: a.contact_id == ^9435,
  select: {a.contact_id, a}

因此,它试图在address中查找contact_id字段,但我希望address属于一个或多个联系人,但我不希望address表中的contact_id字段。如何通过外胚层协会实现这一点

我知道我可以使用一个中间表来实现这一点,该表为每个联系人id和地址id配对一个条目,但我宁愿避免这样做,因为我认为这会增加不必要的复杂性和抽象性


编辑:谢谢你的回答,我意识到我只需要在发帖几分钟后反过来思考。当把它看作一个地址有很多联系人,一个联系人有一个地址时,这种关系是有意义的。我一直认为地址属于某个联系人,但这不一定是真的。

如果一个
联系人只能有一个
地址,而
地址可以在多个
联系人中,并且
联系人表中有一个
地址id
字段,您需要一个
属于
联系人中的
关系,而
联系人中有许多

schema "contacts" do
  belongs_to :address, App.Address
  ...
end

schema "addresses" do
  has_many :contact, App.Contact
  ...
end
现在,您可以获得联系人的地址,如下所示:

contact = Repo.get(Contact, 1234) |> Repo.preload([:address])
IO.inspect contact.address.name

这是一个正常的一对多关联。您应该使用
属于
而不是
拥有一个
。这就是定义外键的地方。你可以阅读更多关于它们之间区别的内容

联系人迁移应具有关联行,例如

add:address\u id,references(:address,on\u delete::nothing)

那么您的模式应该具有以下关系

schema "contacts" do
  belongs_to :address, App.Address
end

schema "addresses" do
  has_many :contact, App.Contact
end

如果在这些调整之后仍然出现错误,那么这可能是控制器/查询中的另一个错误,我们需要更多代码示例来帮助您

“但我不希望地址表中的联系人id字段”那么数据库中的记录将如何关联?许多联系人可以共享一个地址。但每个触点只有一个加法器。