Reputation: 331
I have 2 tables, with relation one to many.
I create 2 entity's on this tables. But when I try get data created third table and in exist tables add new fields.
My tables
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;
My entity's
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 = {
}
}
After using grails, change in mysql tables
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;
So, how fix this problem? Why grails change my tables?
Upvotes: 0
Views: 185
Reputation:
The problem is that you declared:
static belongsTo = Question
But this makes the relation unidirectional, since you cannot query this belongsTo. In this case Grails will use a join table. If you don't want the join table, you need to make it bidirectional, by declaring:
static belongsTo = [question: Question]
More information about this here.
Upvotes: 1