Define a unique primary key based on 2 columns

后端 未结 7 583
长情又很酷
长情又很酷 2021-01-31 02:52

I would like to define a unique key for records based on 2 columns : \'id\' and \'language\'

to let the user submits the following strings : id=1 language=en value=bl

7条回答
  •  无人及你
    2021-01-31 03:35

    I faced a similar problem when migrating a site to Rails. I had a table which stores text data for each language my site is available in so I had something like this:

    CREATE TABLE Project_Lang(
        project_id INT NOT NULL,
        language_id INT NOT NULL,
        title VARCHAR(80),
        description TEXT,
    
        PRIMARY KEY pk_Project_Lang(project_id, language_id),
    
        FOREIGN KEY fk_Project_Lang_Project(project_id)
            REFERENCES Project(project_id)
            ON DELETE RESTRICT ON UPDATE CASCADE,
    
        FOREIGN KEY fk_Project_Lang_Language(language_id)
            REFERENCES Language(language_id)
            ON DELETE RESTRICT ON UPDATE CASCADE
    )ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 DEFAULT COLLATE = utf8_spanish_ci;
    

    But since Rails doesn't handle composite primary keys out of the box I was forced to change the structure of the table so it had it's own primary key:

    CREATE TABLE Project_Lang(
        project_lang_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
        project_id INT NOT NULL,
        language_id INT NOT NULL,
        title VARCHAR(80),
        description TEXT,
    
        UNIQUE INDEX(project_id, language_id),
    
        FOREIGN KEY fk_Project_Lang_Project(project_id)
            REFERENCES Project(project_id)
            ON DELETE RESTRICT ON UPDATE CASCADE,
    
        FOREIGN KEY fk_Project_Lang_Language(language_id)
            REFERENCES Language(language_id)
            ON DELETE RESTRICT ON UPDATE CASCADE
    )ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 DEFAULT COLLATE = utf8_spanish_ci;
    

    I also created a unique index for the columns that previously made the composite primary key so that no duplicate record is inserted. Then in my Rails model I could simply:

    self.primary_key = "project_lang_id"
    

    And that did the trick. Is not what I wanted but is better than fighting the framework.

提交回复
热议问题