Symfony排序模型有请求

时间:2011-10-11 13:32:57

标签: symfony1 doctrine symfony-1.4

我有两个模型:Operation和OperationHistory

Operation:
  columns:
    startdate:      { type: timestamp, notnull: true }
    enddate:        { type: timestamp, notnull: true }
    year:           { type: integer, notnull: true }
    abscomment:     { type: string(500) }
    person_id:      { type: integer, notnull: true }
    operationtype_id: { type: integer, notnull: true }
  relations:
    Person:        { onDelete: CASCADE, local: person_id, foreign: id, foreignAlias: Operations}
    OperationType:   { onDelete: CASCADE, local: absencetype_id, foreign: id, foreignAlias: Operations }

OperationHistory:
  columns:
    oh_comment:      { type: string(500), notnull: true }
    oh_date:         { type: timestamp, notnull: true }
    status_id:      { type: integer, notnull: true }
    operation_id:     { type: integer, notnull: true }
    updater:        { type: integer, notnull: true }
  indexes:
    date:
      fields:
        ohdate:
          sorting: DESC
  relations:
    Operation:        { onDelete: CASCADE, local: operation_id, foreign: id, foreignAlias: OperationsHistory }
    Person:         { onDelete: CASCADE, local: updater, foreign: id, foreignAlias: OperationsHistory }
    OperationStatus:  { onDelete: CASCADE, local: status_id, foreign: id, foreignAlias: OperationsHistory }

为了获得所有Person by Operation,我在OperationHistory上使用了一个索引。因此,如果我需要具有特定状态的所有人的操作:

public function getOperations($person, $status){
  $q = $this->createQuery('o')
    ->leftJoin('o.OperationsHistory oh')
    ->leftJoin('p.Person p')
    ->groupBy('ah.absence_id')
    ->having('ah.status_id = ?', $status);

  return $q->execute();
}

由于ohdate上的索引,我假设使用groupBy,我只获得有关特定操作的最后一个OperationHistory。没有having子句,这很好,但我只想要具有特定状态的操作。但是,如果我设置这个条款,我什么也得不到。

实际上,我需要翻译这个sql请求:

SELECT *
FROM operation o
LEFT JOIN (
  SELECT *
  FROM operation_history
  ORDER BY ohdate DESC
) oh ON o.id = oh.absence_id
LEFT JOIN person p ON p.id = o.person_id
WHERE p.id = 1
GROUP BY oh.operation_id
HAVING oh.status_id = 1
抱歉我的英语不好,我希望这些信息能帮助我。

谢谢你!

2 个答案:

答案 0 :(得分:0)

根据您上面的问题很难理解您要做的事情 - 您能否包含其他一些信息?

您可以使用Doctrine_Query类的joinorderby方法:

$query = Doctrine_Core::getTable('operation')->createQuery()
->innerjoin('operation_history ......')
->orderby('.....')

答案 1 :(得分:0)

通过使用Doctrine_RawSql(),它可以工作!

public function getAbsenceQueries($person, $status){
    $q = new  Doctrine_RawSql();
    $q->select('{o.*}, {oh.*}')
      ->from('operation o LEFT JOIN (SELECT * from operation_history order by ohdate DESC) oh ON o.id=oh.operation_id LEFT JOIN person p ON p.id = o.person_id')
      ->where('mg.group_id = ?', $group)
      ->groupBy('ah.absence_id')
      ->having('ah.status_id = ?', $status)
      ->addComponent('o','Operation o')
      ->addComponent('oh','o.OperationsHistory oh')
      ->addComponent('p','o.Person p');

    return $q->execute();
}