如何在sequelize中的多个列上定义唯一索引 [英] How to define unique index on multiple columns in sequelize

查看:103
本文介绍了如何在sequelize中的多个列上定义唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在sequelize中的列组合上定义唯一索引.例如,我想在user_id,count和name上添加唯一索引.

How do I define a unique index on a combination of columns in sequelize. For example I want to add a unique index on user_id, count and name.

var Tag = sequelize.define('Tag', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        user_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
        },
        count: {
            type: DataTypes.INTEGER(11),
            allowNull: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: true,
        })

推荐答案

您可以参考此文档您将需要更改您的定义,如下所示,并调用同步

You will need to change your definition like shown below and call sync

var Tag = sequelize.define('Tag', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    user_id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
    },
    count: {
        type: DataTypes.INTEGER(11),
        allowNull: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: true,
    }
},
{
    indexes: [
        {
            unique: true,
            fields: ['user_id', 'count', 'name']
        }
    ]
});

这篇关于如何在sequelize中的多个列上定义唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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