Doctrine查询帮助

时间:2011-04-27 08:17:07

标签: zend-framework doctrine

我需要使用doctrine执行sql查询。查询非常简单

  

SELECT q。*,COUNT(a.question_id)FROM   问题AS q LEFT JOIN   question_answers AS ON   q.id = a.question_id GROUP BY   a.question_id

为此,我写了以下代码

    $query = Doctrine_Query::create()
             ->select('q.*, COUNT(a.question_id) AS answers')
             ->from('Model_Question q')
             ->leftJoin('Model_QuestionAnswers a ON q.id = a.question_id')
             ->groupBy('a.question_id');

但这不是我想要的查询。谁能解释一下我错过了什么?我通过$query->buildSqlQuery()检查生成的查询是

SELECT q.id AS q__id, q.title AS q__title, q.short_description AS q__short_description, 
q.created_at AS q__created_at, q.updated_at AS q__updated_at, q.is_visible AS 
q__is_visible, q.category_id AS q__category_id, q.user_id AS q__user_id, q.category_name 
AS q__category_name, q.username AS q__username, COUNT(q2.question_id) AS q2__0 FROM 
question q, question_answers q2 GROUP BY q2.question_id

1 个答案:

答案 0 :(得分:1)

因为您没有在表和模型名称之间使用标准命名约定,所以Doctrine对连接感到困惑。我怀疑你也可能没有定义模型/表之间的关系,以便Doctrine可以自动为你建立连接。

尝试将该查询中的leftJoin()调用更改为:

->leftJoin('q.Model_QuestionAnswers a')

您可能需要在schema.yml文件中明确定义关系,以便像上面这样简单的语句。例如,在Model_QuestionAnswers定义的末尾,您将添加:

relations:
  Model_Question: 
    local: question_id
    foreign: id
    foreignAlias: Model_QuestionAnswers

另外还有一个注意事项:我注意到你的表格和模型都使用了单数和复数名称。通常选择其中一个并坚持使用它,特别是当您使用需要能够猜测名称和自动生成代码的框架和/或ORM时。我正在使用Doctrine和Symfony框架。至少在该上下文中,模型和表名按惯例是单数的。