简体   繁体   English

对两个表格进行独特约束

[英]Sequelize Unique Constraint Across Two Tables

I have three tables: survey, survey_owners (join table), users. 我有三个表:survey,survey_owners(连接表),用户。 Surveys naturally have titles and are owned by users. 调查自然具有标题并由用户拥有。 A user can own multiple surveys and a survey can be owned by multiple users (many-to-many relationship). 用户可以拥有多个调查,并且调查可以由多个用户拥有(多对多关系)。

I have the unique constraint setup on the survey_owners table so there are no duplicates, but now need to figure out how to enforce a unique constraint to address the following: A user should not be able to own multiple surveys with the same title. 我在survey_owners表上有唯一的约束设置,因此没有重复项,但现在需要弄清楚如何强制执行唯一约束来解决以下问题:用户不应该拥有具有相同标题的多个调查。

That being said, a unique constraint CANNOT be placed on the 'title' column of the survey table because the uniqueness should be only be applied if a user already owns a survey with an identical name. 话虽如此,唯一约束不能放在调查表的“标题”列上,因为只有在用户已拥有具有相同名称的调查时才应用唯一性。

Any ideas how to implement this in the Sequelize migration and/or model(s)? 任何想法如何在Sequelize迁移和/或模型中实现这一点?

Current migration file for survey_owners survey_owners的当前迁移文件

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('survey_owners', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      surveys_id: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        references: {
          model: 'surveys',
          key: 'id'
        }
      },
      users_id: {
        type: Sequelize.INTEGER,
        references: {
            model: 'users',
            key: 'id'
        }
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
        field: "created_at"
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
        field: "updated_at"
      }
    })
    .then(() => {
      return queryInterface.addConstraint('survey_owners', ['surveys_id', 'users_id'], {
          type: 'unique',
          name: 'survey_owners'
      });
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('survey_owners');
  }
};

Unfortunately I could not find a way inside Sequelize to handle this constraint so I am handling the logic on the submit action and checking in a JS method. 不幸的是我无法在Sequelize中找到一种方法来处理这个约束,所以我正在处理提交操作的逻辑并检查JS方法。 Not the best way but had to move on and this is working. 不是最好的方式,但不得不继续前进,这是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM