简体   繁体   English

有条件加入 Doctrine?

[英]Conditional joins in Doctrine?

I've two tables, location and forecast.我有两张表,位置和预测。 I'd like to query the database to find all locations that match forecast parameters for each day.我想查询数据库以查找与每天的预测参数匹配的所有位置。

eg London has forecast entries for the days 2011-07-13, 2011-07-14, 2011-07-15, and 2011-07-16.例如,伦敦有 2011-07-13、2011-07-14、2011-07-15 和 2011-07-16 天的预测条目。 I'd like London to be returned if on 2011-07-14 AND 2011-07-15 the temperature is not higher than 40 and not lower than 13.如果 2011-07-14 和 2011-07-15 的温度不高于 40 且不低于 13,我希望返回伦敦。

I've managed to work this out in MySQL (I think):我已经设法在 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';

I attempted to translate this into Doctrine, but I'm getting memory exhausted errors.我试图将其翻译成 Doctrine,但我收到 memory 耗尽错误。 My Doctrine query:我的 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();

What is the correct & most efficient way of running this query?运行此查询的正确和最有效的方法是什么? I'm pretty sure I'm doing something fundamentally wrong.我很确定我在做一些根本错误的事情。

Many thanks in advance提前谢谢了
Pete皮特

I think it would be easier to use $query->addWhere('EXISTS (...)') with an inner select statement for each condition.我认为将$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM