我有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会改变我的桌子?
答案 0 :(得分:1)
问题是您声明了:
static belongsTo = Question
但这会使关系单向,因为您无法查询此belongsTo。在这种情况下,Grails将使用连接表。如果您不想要连接表,则需要通过声明:
使其成为双向的static belongsTo = [question: Question]
有关此here的更多信息。