700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > mysql数据库唯一性_在MySQL数据库中添加唯一性约束 范围可能吗?

mysql数据库唯一性_在MySQL数据库中添加唯一性约束 范围可能吗?

时间:2020-07-19 12:25:02

相关推荐

mysql数据库唯一性_在MySQL数据库中添加唯一性约束 范围可能吗?

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

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

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表中我有这样的条目:

+---------+-------------+

| dish_id | category_id |

+---------+-------------+

| 3 | 5 |

| 3 | 1 |

| 2 | 1 |

+---------+-------------+我想确保你没有办法做出这样的另一个条目:

+---------+-------------+

| dish_id | category_id |

+---------+-------------+

| 3 | 5 |

| 3 | 1 |

| 2 | 1 |

| 2 | 1 |

+---------+-------------+我知道有一种方法可以通过Rails来实现,但是有没有办法通过MySQL来防止这种情况?

我知道在MySQL中使用:

ALTER TABLE category_pairings

ADD UNIQUE (category_id);但是这样做可以让整个表格只能有一个唯一的category_id。

如果只有通过Rails才能做到这一点,那么我的新迁移将如何实现?

这是我原来的迁移看起来像创建category_pairings表:

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。