Squeryl关系1:N

时间:2016-02-24 20:20:57

标签: mysql scala squeryl

我遇到了Squeryl ORM的一些麻烦。非常基本的功能,如选择或插入行没有关系工作正常,问题开始时,我尝试获取关系1:N的数据在琐碎的情况下。 在测试DB中,我创建两个表问题和答案。一个问题可以包含几个答案。这是表创建SQL:

DROP TABLE IF EXISTS `questions`;
CREATE TABLE `questions` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `nid` int(11) NOT NULL,
  `text` text NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `questions` (`id`, `nid`, `text`, `active`)
VALUES
(1,1,'test question',1),
(2,2,'second question',1);

DROP TABLE IF EXISTS `answers`;
CREATE TABLE `answers` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `question_id` int(11) unsigned NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `qwerty` (`question_id`),
  CONSTRAINT `qwerty` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `answers` (`id`, `question_id`, `text`)
VALUES
(1,1,'test answer');

这是带有模型类的Scala代码:

class BaseEntity extends KeyedEntity[Long] { val id: Long = 0 }

class Question(var nid: Long, var text: String, 
      var active: Integer) extends BaseEntity {

    def this() = this(0, "", 1)
    lazy val Answers: List[Answer] = DataBase.answersToQuestion.left(this).toList
}

class Answer(var question_id: Long, var text: String) extends BaseEntity { 
    def this() = this(0, "")
    lazy val Question: Question = DataBase.answersToQuestion.right(this).head
}

object DataBase extends Schema {
    val questions = table[Question]("questions")
    val answers = table[Answer]("answers")
    val answersToQuestion = oneToManyRelation(questions, answers)
        .via((q, a) => q.id === a.question_id)

    on(answers)(a => declare( a.id is (autoIncremented) ))
    on(questions)(q => declare( q.id is (autoIncremented) ))
}

所以在数据选择上我得到完整的Question对象,但Answers始终为null。

var question: Option[Question] = inTransaction { DataBase.questions.lookup(1L) }
//question.Answers is null !!

有人可以看看,告诉我,我的错误是什么?

1 个答案:

答案 0 :(得分:0)

也许我只是希望另一种行为或错误配置的ORM,虽然我在调试器中得到null,但是对于Answer类来说这样做很好:

def getQuestion = inTransaction(Question.headOption)

这样问题:

def getAnswers = inTransaction(Answers.toList)

希望这对那些不熟悉Squeryl且遇到与我一样的问题的人有所帮助。

到目前为止,不要将问题标记为答案,因为可能有更好的解决方案。