NODEJS sequelize中聯合唯一索引的實現

查了半天API文檔,仔細看才發現這麼一條

[attributes.column.unique=false] String | Boolean If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index
意思是unique這個屬性可以爲字符串也可以爲bool型

假如爲bool型的true,則表示單個這個列建唯一索引

假如爲字符串,別的列中使用相同字符串的跟這個組成聯合唯一索引,所以就實現了

"use strict";

module.exports = function (sequelize, DataTypes) {
    var Store = sequelize.define("Store", {
        storeId:{type:DataTypes.INTEGER, primaryKey: true,  autoIncrement: true},
        name: {type:DataTypes.STRING, unique:"uk_t_store"},
        address: DataTypes.STRING,
        status: {type: DataTypes.INTEGER, defaultValue: 1},
        areaId: {type:DataTypes.UUID,allowNull: false, unique:"uk_t_store"}
    }, {
        tableName: 't_store'
    });
    return Store;
};

本例中,areaId同時又是外鍵,關聯一張area表,可以這麼寫

db['Store'].belongsTo(db['Area'], {foreignKey: "areaId", constraints: false});

同時附上另一張表的表結構

"use strict";

module.exports = function (sequelize, DataTypes) {
    var Area = sequelize.define("Area", {
        //區域ID
        areaId: {type: DataTypes.UUID, primaryKey: true, allowNull: false, defaultValue: DataTypes.UUIDV4},
        //區域名
        name: {type:DataTypes.STRING, unique:"uk_t_area"},
        //區域狀態  1-啓用 0-禁用
        status: {type: DataTypes.INTEGER, defaultValue: 1}

    }, {
        tableName: 't_area'
    });
    return Area;
};


發佈了84 篇原創文章 · 獲贊 110 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章