How to set belongs to for multiple fields to the same table

Hi,

Please i have a customer table and the table has created_by and approved_by as below

defmodule Commercial.Banking.Customer do
  use Ecto.Schema
  use Arc.Ecto.Schema

  import Ecto.Changeset
  # import Ecto.Query

  alias Commercial.Banking.Customer

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "customers" do
    field :employers_name, :string
    field :spouse_name, :string
    field :employed, :boolean, default: false
    field :local_government, :string
    field :title, :string
    field :email, :string
    field :business_occupation, :string
    belongs_to :nationality, Commercial.Banking.Nationality
    belongs_to :branch, Commercial.Accounts.Branch
    many_to_many :account, Commercial.Banking.AccountType, join_through: "customers_account_type"
    field :business_address, :string
    field :next_of_kin_name, :string
    field :approved_by, :binary_id
    # belongs_to :user_approved, Commercial.Accounts.User, source: :approved_by
    field :date_of_birth, :date
    field :phone_number, :string
    field :passport, Commercial.Modules.Avatar.Type
    field :commercial_bank_account, :string
    field :account_number, :string
    field :residential_address, :string
    field :firstname, :string
    field :commercial_bvn, :string
    field :date_of_employment, :date
    field :state_of_origin, :string
    field :next_of_kin_relationship, :string
    field :next_of_kin_phone_number, :string
    field :surname, :string
    field :middlename, :string
    field :commercial_bank_name, :string
    field :created_by, :binary_id
    # belongs_to :creator, Commercial.Accounts.User, source: :created_by
    field :mothers_maiden_name, :string
    field :date_created, :date
    field :spouse_phone_number, :string
    field :passbook_number, :string

    timestamps()
  end

I have tried using something similar like below

belongs_to :user_approved, Commercial.Accounts.User, source: :approved_by
belongs_to :creator, Commercial.Accounts.User, source: :created_by

but it didn’t work. Please how can i achieve this?

Thank you.

Thank you all. I already found a solution in this post Belongs_to, multiple foreign keys?

1 Like