在Ecto中一起在两列上创建唯一约束 [英] Creating a unique constraint on two columns together in Ecto

查看:43
本文介绍了在Ecto中一起在两列上创建唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ecto的两列上创建唯一索引,该索引对应于以下内容:

How do you create a unique index on two columns in Ecto, which would correspond to this:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    primary key (col1, col2)
)

推荐答案

对Patrick的回答稍作跟进

A Little follow up on Patrick's answer

仅在模型上创建unique_index最终会引发异常,而不是给您错误。

Using only create unique_index on your model will ultimately throw an exception instead of giving you an error.

要获取错误,请添加

因此在您的迁移文件中:

So in your migration file :

create unique_index(:your_table, [:col1, :col2], name: :your_index_name)

然后在您的变更集中:

def changeset(model, param \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> unique_constraint(:name_your_constraint, name: :your_index_name)
end

这篇关于在Ecto中一起在两列上创建唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆