如何在Ecto中使用复杂约束?

时间:2018-05-24 21:01:07

标签: elixir phoenix-framework ecto

这就是我想要实现的目标

@change="sendData()"

所以我确实喜欢这个......

1. Customer can create a contact with name and phone number.
2. Customer can not create a contact with already existing phone number.

并在迁移文件中

schema "people" do
    field :name, :string
    field :phone_number, :string
    belongs_to :phonebook, Phonebook

    timestamps()
  end

  def changeset(%Person{} = person, attrs) do
    person
    |> cast(attrs, [:name, :phone_number])
    |> validate_required([:name, :phone_number])
    |> unique_constraint(:phone_number])
  end

但是其他客户无法创建具有相同号码的联系人,因为其他客户可能具有相同的号码。 那么这个解决方案是什么?我查看了Ecto文档并找到了https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3 1

复杂约束

这是正确的解决方案吗? 我已按照文档记录了这一点,但它不起作用。

1 个答案:

答案 0 :(得分:2)

一种方法是在架构中使用customer_id字段。然后将唯一约束应用于phone_numbercustomer_id字段。在这种情况下,电话号码将由添加的客户确定范围。当客户创建联系人时,将联系人的customer_id设置为客户的ID

在迁移文件

create table(:people) do
  ...
  add :customer_id, :integer
end

create unique_index(:people, [:phone_number, :customer_id], name: :people_phone_number_customer_id_index)

在模型模块中

schema "people" do
field :name, :string
field :phone_number, :string
field :customer_id, :integer
belongs_to :phonebook, Phonebook

timestamps()

def changeset(%Person{} = person, attrs) do
person
|> cast(attrs, [:name, :phone_number, :customer_id])
|> validate_required([:name, :phone_number, :customer_id])
|> unique_constraint(:phone_number, name: :people_phone_number_customer_id_index)
end