Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNION syntax in Cakephp

Anyone knows a good way to make UNION query in CakePHP? I would like to avoid using $this->query();.

With two tables t1, t2:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

With three tables t1, t2, t3:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id
like image 935
bancer Avatar asked Aug 21 '10 03:08

bancer


People also ask

How can I get query string in CakePHP?

In CakePHP 2.0 this appears to have changed. According to the documentation you can access $this->request->query or $this->request['url'] .

What is contain in CakePHP?

A new addition to the CakePHP 1.2 core is the ContainableBehavior . This model behavior allows you to filter and limit model find operations. Using Containable will help you cut down on needless wear and tear on your database, increasing the speed and overall performance of your application.

How can I get last query in CakePHP?

$last_query = $ this ->ModelName->getLastQuery(); As we have saved last executed query in variable $last_query then use this to print last executed query.

How can I get data from database in CakePHP?

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.


1 Answers

use a code like this :

$friendsPosts= $this->Posts->find('all')
                ->contain(['Users', 'Languages', 'PostStates'])
                ->innerJoinWith('Users.Dusers', function ($q) {
                    return $q->where(['Dusers.id' => $this->Auth->user('id')]);
                });

        $posts= $this->Posts->find('all')
                ->where(['Posts.post_state_id' => 3])
                ->contain(['Users', 'Languages', 'PostStates']);

    $posts->union($friendsPosts);
like image 162
afsane Avatar answered Sep 18 '22 13:09

afsane