0

我有 2 张桌子,有一对多的关系。

我在这个表上创建了 2 个实体。但是当我尝试创建第三个表并在现有表中添加新字段时。

我的桌子

CREATE TABLE `question` (
    `ID` INT(11) NOT NULL AUTO_INCREMENT,
    `Question` VARCHAR(200) NOT NULL,
    PRIMARY KEY (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;


CREATE TABLE `answer` (
    `ID` INT(10) NOT NULL AUTO_INCREMENT,
    `QuestionID` INT(11) NOT NULL,
    `Answer` VARCHAR(50) NOT NULL,
    `IsCorrect` TINYINT(1) NULL DEFAULT '0',
    PRIMARY KEY (`ID`),
    INDEX `FK_Question` (`QuestionID`),
    CONSTRAINT `FK_Question` FOREIGN KEY (`QuestionID`) REFERENCES `question` (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

我的实体

class Answer {

    int id

    String answer

    boolean isCorrect
    static belongsTo = Question

    static constraints = {
    }

}

class Question {

    int id
    String question
    List<Answer> answers
    static hasMany = [answers : Answer]

    static constraints = {
    }
}

使用grails后,mysql表的变化

CREATE TABLE `question` (
    `ID` INT(11) NOT NULL AUTO_INCREMENT,
    `Question` VARCHAR(200) NOT NULL,
    `version` BIGINT(20) NOT NULL,
    PRIMARY KEY (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=15;

CREATE TABLE `answer` (
    `ID` INT(10) NOT NULL AUTO_INCREMENT,
    `QuestionID` INT(11) NOT NULL,
    `Answer` VARCHAR(50) NOT NULL,
    `IsCorrect` TINYINT(1) NULL DEFAULT '0',
    `version` BIGINT(20) NOT NULL,
    `is_correct` BIT(1) NOT NULL,
    PRIMARY KEY (`ID`),
    INDEX `FK_Question` (`QuestionID`),
    CONSTRAINT `FK_Question` FOREIGN KEY (`QuestionID`) REFERENCES `question` (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=32;

CREATE TABLE `question_answer` (
    `question_answers_id` INT(11) NULL DEFAULT NULL,
    `answer_id` INT(11) NULL DEFAULT NULL,
    `answers_idx` INT(11) NULL DEFAULT NULL,
    INDEX `FK561DF237111171E9` (`answer_id`),
    CONSTRAINT `FK561DF237111171E9` FOREIGN KEY (`answer_id`) REFERENCES `answer` (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

那么,如何解决这个问题呢?为什么 grails 会改变我的表?

4

1 回答 1

1

问题是您声明:

static belongsTo = Question

但这会使关系单向,因为您无法查询此 belongsTo。在这种情况下,Grails 将使用连接表。如果您不想要连接表,则需要通过声明使其成为双向的:

static belongsTo = [question: Question]

更多关于这里的信息。

于 2013-10-01T16:55:51.150 回答