0
votes

I'm new to PostgreSQL. I have problem in association between parent and child. Let say we have two schemas called TableA and TableB. I need to associate TableA and TableB. In which the primary key of TableA, may or may not be needed in TableB for "specific roles"(I have three roles called E,F and G. For G I do not need an entry in TableB but I need it for rest of the roles). How do I associate. Which association do I need to use, Whether has_many, has_one etc, is there any way to fix this. You may find the link here 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
1

1 Answers

1
votes

Ok, so your business rules were a little confusing to me because of the ABCDEFG thing. But we can still talk about associations!

It looks like you've got an "addresses" table and a "address_roles" table (is that like, "Work" and "Home"?)

Here's how I'd set up those tables in my migrations (and here's the documentation)...

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

...and in the schemas you can provide for the two-way nature of the belongs-to and has-many by doing (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

Is that what you're looking for?