我对Phoenix Elixir中的关联有一个疑问,它发生在插入新客户时,他们之间发生了多个关联,文档架构接收到“ customer_id”以及“联系和债务”架构,所有这些都有效。而且在此事务中,我想将创建的Doc模式的“ doc_id”与Debt模式相关联,这对我不起作用。
客户架构
defmodule App.Customers.Customer do
use Ecto.Schema
import Ecto.Changeset
alias App.Customers.{ Contact, Doc, Debt }
alias App.Collections.Collection
schema "customers" do
field :codLegal, :string
field :businessName, :string
field :fantasyName, :string
has_many :contacts, Contact
has_many :docs, Doc
has_one :collection, Collection
has_many :debts, Debt
timestamps()
end
def changeset(customer, attrs \\ %{}) do
customer
|> cast(attrs, [:codLegal, :businessName, :fantasyName])
|> validate_required([:codLegal, :businessName, :fantasyName])
|> unique_constraint(:codLegal)
|> cast_assoc(:docs, with: &App.Customers.Doc.changeset/2)
|> cast_assoc(:contacts, with: &App.Customers.Contact.changeset/2)
|> cast_assoc(:debts, with: &App.Customers.Debt.changeset/2)
end
end
文档架构
defmodule App.Customers.Doc do
use Ecto.Schema
import Ecto.Changeset
alias App.Customers.{ Doc, Customer, Debt }
alias App.Collections.Collection
schema "docs" do
field :number, :string
field :startdate, :date
field :endate, :date
field :type, :string
belongs_to :customer, Customer
many_to_many :collections, Collection, join_through: "collections_docs"
has_one :debt, Debt
timestamps()
end
@doc false
def changeset(doc, attrs) do
doc
|> cast(attrs, [:type, :number, :startdate, :endate])
|> validate_required([:type, :number, :startdate, :endate])
|> unique_constraint(:number)
|> cast_assoc(:debt, with: &App.Customers.Debt.changeset/2)
end
end
债务架构
defmodule App.Customers.Debt do
use Ecto.Schema
import Ecto.Changeset
alias App.Customers.{ Customer, Doc }
schema "debts" do
field :credit, :integer
field :debit, :integer
belongs_to :doc, Doc
belongs_to :customer, Customer
timestamps()
end
@doc false
def changeset(debt, attrs) do
debt
|> cast(attrs, [:debit, :credit])
|> validate_required([:debit])
end
end