Doctrine中的条件连接?

时间:2011-07-14 10:09:28

标签: php mysql symfony1 doctrine

我有两张桌子,位置和预测。我想查询数据库以查找与每天的预测参数匹配的所有位置。

e.g。伦敦预测了2011-07-13,2011-07-14,2011-07-15和2011-07-16的日期。如果在2011-07-14和2011-07-15温度不高于40且不低于13,我希望伦敦能够归还。

我已经设法在MySQL(我认为)中解决了这个问题:

SELECT f1.day, f1.temperature_high, f1.temperature_low, f2.day, f2.temperature_high, f2.temperature_low, l.name 
FROM location l
INNER JOIN forecast f1 ON 
  f1.location_id = l.id AND 
  f1.day = '2011-07-14' AND 
  f1.temperature_high <= '40' AND 
  f1.temperature_low >= '13'
INNER JOIN forecast f2 ON 
  f2.location_id = l.id AND 
  f2.day = '2011-07-15' AND 
  f2.temperature_high <= '40' AND 
  f2.temperature_low >= '13';

我试图把它翻译成Doctrine,但是我的内存耗尽了错误。我的学说查询:

$this->results = Doctrine_Query::create()->select('l.name')->from('Location l');

foreach ($values['day'] as $i => $day) { $this->results->innerJoin('l.Forecasts f'.$i.' ON f'.$i.'.condition_id IN (' . implode(',', $values['condition']) . ') AND f'.$i.'.temperature_high <= ' .$values['temperature_max'] . ' AND f'.$i.'.temperature_low >= ' . $values['temperature_min']); } $this->results->execute();

什么是正确的&amp;最有效的运行此查询的方法?我很确定我做的事情根本就是错误的。

非常感谢提前 皮特

1 个答案:

答案 0 :(得分:2)

我认为对每个条件使用$query->addWhere('EXISTS (...)')和内部select语句会更容易。

$this->results = Doctrine_Query::create()->select('name')->from('location');

foreach ($values['day'] as $i => $day) {
    $this->results->addWhere('EXISTS (
        SELECT NULL
        FROM forecast
        WHERE location_id = location.id
        AND condition_id IN (' . implode(',', $values['condition']) . ')
        AND temperature_high <= ' . $values['temperature_max'] . '
        AND temperature_low >= ' . $values['temperature_min'] . '
    )');
}
$this->results->execute();