简体   繁体   中英

CakePHP find with LEFT JOIN and generate_series

Basically, is it possible, and if so, how do you do the following code without using the raw query() method in CakePHP 2.0.6. I am using PostgreSQL (which generate_series() is a function of). So, how do you do this query the CakePHP way?

$sql = "
    SELECT new_rank FROM generate_series(1,999) AS new_rank
    LEFT JOIN tasks ON tasks.rank = new_rank
    WHERE tasks.rank IS NULL LIMIT 1
";
$data = $this->Task->query($sql);

EDIT One user said I could try to use the find call on Task and right join to generate_series(). Here is my attempt at that. This code throws an error, in that CakePHP is putting double quotes around the function arguments for generate_series. I wonder how I can get it to not do that?

$data = $this->Task->find('all', array(
   'conditions' => array('Task.rank' => null),
   'limit' => 1,
   'recursive' => -1,
   'fields' => 'new_rank',
   'joins' => array(
      array(
          'table'=>'generate_series(1,999)',
          'alias'=>'new_rank',
          'type'=>'RIGHT',
          'conditions' => array(
            'tasks.rank'=>'new_rank'
          )
      )
   )
));

Which products the following SQL:

SELECT "Task"."new_rank" AS "Task__new_rank"
FROM "tasks" AS "Task"
RIGHT JOIN generate_series("1,999") AS "new_rank" ON ("tasks"."rank" = 'new_rank')
WHERE "Task"."rank" IS NULL LIMIT 1

What you're probably looking for is in DboSource::expression() . It basically allows you to do a SQL expression without any of Cake's escaping. Make sure to sanitize inputs.

To have it show up as a field, you can try adding it to the fields key in your options array:

$ds = $this->Task->getDataSource();
$this->Task->find('all', array(
  'fields' => $ds->expression('generate_series(1,999) AS new_rank')
));

If that doesn't work, you can always try DboSource::rawQuery() which doesn't escape anything , afaik.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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