Elixir phoenix:检查字段组合的唯一约束
我有一个类似于以下内容的db表:Elixir phoenix:检查字段组合的唯一约束,elixir,phoenix-framework,Elixir,Phoenix Framework,我有一个类似于以下内容的db表: 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和INTERT组合的记录不存在 我怎样才能在凤凰城做到这一点? 我在凤凰城做我的第一个项目,所以我知道的不多。 非常感谢您的帮助。在迁移过程中
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和INTERT组合的记录不存在
我怎样才能在凤凰城做到这一点?
我在凤凰城做我的第一个项目,所以我知道的不多。
非常感谢您的帮助。在迁移过程中,您应该定义一个唯一的索引。下面是一个例子:
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
我们不应该在凤凰城做到这一点。检查数据库中记录的唯一性确实是数据库的职责。在数据库中直接对这三个字段创建唯一约束。