phoenix:检查字段组合的唯一约束

phoenix: Check unique constraint for a combination of fields

我有一个数据库 table 类似于以下内容:

UID QID Attempt score
 1   1    1       4
 1   2    1       3
 1   1    2       5
 1   2    2       5
 2   1    1       2
 2   2    1       3

插入新值时,我想确保 UID、QID 和 Attempt 组合的记录不存在。

我怎样才能在凤凰城实现这一目标? 我正在凤凰城开展我的第一个项目,所以了解不多。 感谢任何帮助。

在您的迁移中,您应该定义一个唯一索引。这是一个例子:

defmodule App.Repo.Migrations.CreateFoos do
  use Ecto.Migration

  def change do
    create table(:foos) do # note that you also get an id column as the primary key, but you can disable it with primary_key: false
      add :uid, :integer
      add :qid, :integer
      add :attempt, :integer
      add :score, :integer

      timestamps()
    end

    # tell your db that these columns should be unique
    create unique_index(:foos, [:uid, :qid, :attempt], name: :my_index)
  end
end

在你的架构中,如果你有一个:

defmodule App.Foo do
  use Ecto.Schema

  import Ecto.Changeset

  schema "foos" do
    field :uid, :integer
    field :qid, :integer
    field :attempt, :integer
    field :score, :integer

    timestamps()
  end

  def changeset(foo, attrs) do
    foo
    |> cast(attrs, [:uid, :qid, :attempt, :score])
    |> validate_required([:uid, :qid, :attempt, :score])
    |> unique_constraint(:my_constraint, name: :my_index) # tell ecto that there's a unique constraint
  end
end