首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MySQL数据库上添加唯一约束并允许作用域?

在MySQL数据库上添加唯一约束并允许作用域?
EN

Stack Overflow用户
提问于 2012-08-17 01:46:00
回答 1查看 764关注 0票数 2

我有一个使用MySQL的Rails应用程序。

我有两个模型之间的has_many :through关联,如下所述:

代码语言:javascript
复制
class Category < ActiveRecord::Base
  has_many :category_pairings
  has_many :dishes, through: :category_pairings, :inverse_of => :categories
end

class Dish < ActiveRecord::Base
  has_many :category_pairings
  has_many :categories, through: :category_pairings, :inverse_of => :dishes
end

class CategoryPairing < ActiveRecord::Base
  belongs_to :dish
  belongs_to :category
end

因此,在我的category_pairings表中,我有这样的条目:

代码语言:javascript
复制
+---------+-------------+
| dish_id | category_id |
+---------+-------------+
|       3 |           5 |
|       3 |           1 |
|       2 |           1 |
+---------+-------------+

我想确保您不能再输入这样的条目:

代码语言:javascript
复制
+---------+-------------+
| dish_id | category_id |
+---------+-------------+
|       3 |           5 |
|       3 |           1 |
|       2 |           1 |
|       2 |           1 | <-- Illegal
+---------+-------------+

我知道有一种方法可以通过Rails做到这一点,但是有没有办法通过MySQL来防止这种情况发生呢?

我知道如何在MySQL中使用:

代码语言:javascript
复制
ALTER TABLE category_pairings
ADD UNIQUE (category_id);

但这将使您在整个表中只能有一个唯一的category_id

如果只有通过Rails才能做到这一点,我的新迁移应该是什么样子才能做到这一点?

这是我最初的迁移创建category_pairings表时的样子:

代码语言:javascript
复制
class CreateCategoryPairings < ActiveRecord::Migration
  def change
    create_table :category_pairings do |t|
      t.belongs_to :dish
      t.belongs_to :category

      t.timestamps
    end

    add_index :category_pairings, :dish_id
    add_index :category_pairings, :category_id
  end
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-17 02:10:51

您需要跨两个字段添加一个唯一索引,如下所示:

代码语言:javascript
复制
ALTER TABLE category_pairings
ADD UNIQUE (dish_id, category_id);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11992710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档