简体   繁体   中英

How can I do sql union in cake php?

I have to get all the associative data for the model. Basically the UNION query is as below:

  SELECT * FROM `videos` AS `U1` 
  WHERE `U1`.`level_id` = '1' AND `U1`.`submitted_date` > '2011-09-11'
UNION 
  SELECT * FROM `videos` AS `U2`
  WHERE `U2`.`level_id` = '1' AND `U2`.`submitted_date` < '2011-09-11'
  ORDER BY  submitted_date DESC
  LIMIT 0,10

So when I use $this->Video->find('all')--> I get all the result of the associated table datas.

Now I want to use the UNION SQL query and that should return associated table data too...

Any ideas how to use the cake inbuilt function to get data?

You can do this in 4 or more different ways... the easiest but not recomended is using

$this->Model->query($query); 

where $query is the query stated above.

The second way but may not be what you want, is to redo your sql query you will get same result (but not separated with the alias) like this:

SELECT * FROM `videos` AS `U1` 
WHERE `U1`.`level_id` = '1' AND (`U1`.`submitted_date` > '2011-09-11' OR `U1`.`submitted_date` < '2011-09-11')
ORDER BY  submitted_date DESC
LIMIT 0,10

This query can be easily done with find like this

$conditions = array(
    'Video.level_id'=>1,
    'OR' => array(
        'Video.submitted_date <'=> '2011-09-11',
        'Video.submitted_date >'=> '2011-09-11'
    )
);
$this->Video->find('all', array('conditions'=>$conditions)) 

The third way will be the one that Abba Bryant talk about, explained in detail here Union syntax in cakePhp that works building the statement directly.

The fourth way will like the first one more less, you will have to create a behaviour that have a beforeFind function and there you will have to check if a option union and create the query or to create something like the the third option.

you will call it with a find like this

$this->Video->find('all', array('conditions'=>$conditions, 'union'=> $union));

This will be something more less like the linkable or containable behavior.

The fith way is to modified your cakephp sql driver... this one, i don't really know the changes you have to do, but it is a way to get to that... This drivers are the responsible to interpret and create the queries, connect to db and execute the queries...

REMEMBER that cakephp find do the checks neccesary to prevent SQLInyection and other risks... the $model->query will NOT do this tests so be carefull

This question here uses joins and the some direct datasource access to build a union query that can be used via the find method.

It is a bit of work, and the code won't be 100% appropriate for you - you will have to modify it - but it should get you started.

UNION syntax in Cakephp

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