日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/8 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的mysql数据库唯一性_在MySQL数据库中添加唯一性约束,范围可能吗?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。