【问题标题】:Association in PostgreSQL through Ecto通过 Ecto 在 PostgreSQL 中关联
【发布时间】:2018-05-18 07:14:33
【问题描述】:

我是 PostgreSQL 新手。我在父母和孩子之间的联系上有问题。 假设我们有两个模式,称为 TableA 和 TableB。 我需要关联 TableA 和 TableB。其中 TableA 的主键在 TableB 中可能需要也可能不需要用于“特定角色”(我有三个角色,称为 E、F 和 G。对于 G,我不需要 TableB 中的条目,但我需要它的其余部分角色)。我怎么关联。我需要使用哪个关联,has_many、has_one 等,有什么办法可以解决这个问题。你可以在这里找到链接Ecto Schema

TableA Schema

    schema "TableA" do
      field :name, :string
      field :role, :string
      field :status, :string

      timestamps()
    end

TableB Schema

    schema "TableB" do
      field :address1, :string
      field :address2, :string
      field :city, :string
      field :companyname, :string
      field :contactno, :string
      field :country, :string
      field :email, :string
      field :mobileno, :string
      field :state, :string
      field :status, :string
      field :type, :string
      field :zipcode, :string

      timestamps()
    end

【问题讨论】:

    标签: postgresql elixir phoenix-framework ecto


    【解决方案1】:

    好的,由于 ABCDEFG 的事情,您的业务规则让我有点困惑。但是我们仍然可以谈论关联!

    看起来你有一个“addresses”表和一个“address_roles”表(是像“Work”和“Home”吗?)

    这是我在迁移中设置这些表的方式 (and here's the documentation)...

    def change do
      alter table("addresses") do
        add :address_role_id, references("address_roles")
      end
    end
    

    ...在模式中,您可以通过 (and here's the documentation)... 来提供属于和拥有的双向性质...

    defmodule MyApp.Address do
      schema "addresses" do
        has_many :address_roles, MyApp.AddressRole
      end
    end
    
    defmodule MyApp.AddressRole do
      schema "address_roles" do
        belongs_to :address, MyApp.Address
      end
    end
    

    这就是你要找的吗?

    【讨论】:

    • 首先感谢您的回答,假设我有 3 个表,分别是我的用户、userRole 和人员表。对于特定的 userRoles,我在人员表中有一个条目。因此,正如您建议的“has_many”关联,它将解决我的问题,因为当前模式具有其他模式的零个或多个记录。另一个模式通常具有带反向关联的 belongs_to 字段。再次感谢。
    • 你有一个上面的例子。尝试将关联代码映射到这个新用例。让我知道您这次尝试了什么,我很乐意从那里帮助调试!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多