UNION syntax in Cakephp - php

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

Too many coders try to limit themselves to the functionality of a framework. DON'T. Use what the framework provides. If it does not have the functionality you seek, then either:
Code the functionality you need into a class extension
or
Custom spin the code within the framework to suit your needs.
Often, developers try to hammer a square peg into a round hole and wind up doing way too much extra work that really only makes the code complicated. Take a step back and ask why you are using the framework to begin with. It brings structure to an unstructured language. It provides solid reusable foundation to build your application on. It is not intended to be a box to put yourself in and be limited.
UPDATE: I took a minute to read Complex Find Conditions and found your answer:
$joins = array(
array(
'table' => 'test_twos',
'alias' => 'TestTwo',
'type' => 'LEFT',
'conditions' => array(
'TestTwo.id = TestOne.id',
)
),
array(
'table' => 'test_threes',
'alias' => 'TestThree',
'type' => 'LEFT',
'conditions' => array(
'TestThree.id = TestOne.id',
)
)
);
$dbo = $this->getDataSource();
$subQuery = $dbo->buildStatement(
array(
'fields' => array('*'),
'table' => $dbo->fullTableName($this),
'alias' => 'TestOne',
'limit' => null,
'offset' => null,
'joins' => $joins,
'conditions' => null,
'order' => null,
'group' => null
),
$this->TestOne
);
$query = $subQuery;
$query .= ' UNION ';
$joins = array(
array(
'table' => 'test_twos',
'alias' => 'TestTwo',
'type' => 'LEFT',
'conditions' => array(
'TestTwo.id = TestOne.id',
)
),
array(
'table' => 'test_threes',
'alias' => 'TestThree',
'type' => 'RIGHT',
'conditions' => array(
'TestThree.id = TestOne.id',
)
)
);
$dbo = $this->getDataSource();
$subQuery = $dbo->buildStatement(
array(
'fields' => array('*'),
'table' => $dbo->fullTableName($this),
'alias' => 'TestOne',
'limit' => null,
'offset' => null,
'joins' => $joins,
'conditions' => null,
'order' => null,
'group' => null
),
$this->TestOne
);
$query .= $subQuery;
pr($query);

A simple way to do this, which we currently use, is to create a view in MySQL or whatever database you use. Then, instead of using a table in your model, you use your view. You can read about view creation syntax here: http://dev.mysql.com/doc/refman/5.6/en/create-view.html. You could also use software like HeidiSQL to help you with view creation.
You would then have something like this in your model :
class Contenu extends AppModel {
public $useTable = 'v_contenu';
This allows you to still use the find() method in CakePHP, which is really nice to have.
To get the best performance with views you should update MySQL to at least version 5.6.

Use a view, then select from that:
create view my_union as
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
In your code:
select * from my_union

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);

Related

CakePHP Translate: Getting group by latest date

How do I translate below to cakePHP code? The code below comes from a solution here MySQL order by before group by.
Getting the author's latest post using group by.
SELECT p1.*
FROM wp_posts p1
INNER JOIN
(
SELECT max(post_date) MaxPostDate, post_author
FROM wp_posts
WHERE post_status='publish'
AND post_type='post'
GROUP BY post_author
) p2
ON p1.post_author = p2.post_author
AND p1.post_date = p2.MaxPostDate
WHERE p1.post_status='publish'
AND p1.post_type='post'
order by p1.post_date desc
Below is still similar situation:
SELECT t1.* FROM payment_status t1
JOIN (SELECT payment_id, MAX(created) max_created
FROM payment_status
GROUP BY payment_id
) t2
ON t1.payment_id = t2.payment_id AND t1.created = t2.max_created;
I need some cakePHP translation for either the two mySQL statements.
------------------------------------------------------------------------------------
I did something like the code below but it gives me error
Error: SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'SELECT max(dateEncoded) maxDate, findings FROM maintain GROUP BY computer_id Office.main_office LIKE' is too long
How do I fix it?
$this->Computer->unbindModel(array(
'belongsTo' => array('Office'),
'hasMany' => array('Brand','Maintain')
));
$model_view = $this->Computer->bindModel(array(
'hasOne' => array(
'Office' => array(
'foreignKey' => false,
'conditions' => array('Office.id = Computer.office_id')
),
'Maintain' => array(
'foreignKey' => false,
'conditions' => array('Computer.id = Maintain.computer_id'),
)
)
)
);
$main_office = trim($this->request->data['Office']['office_id']);
$joins = array(
array(
'table' => "SELECT max(dateEncoded) maxDate, findings FROM maintain GROUP BY computer_id",
'alias' => 'P2',
'type' => 'INNER',
'conditions' => array('Maintain.findings = p2.findings','Maintain.dateEncoded = p2.maxDate')
)
);
$conditions=array("Office.main_office LIKE"=>"%$main_office%");
$result = $this->Computer->find('all',array(
$model_view,
'joins'=>$joins,
'conditions'=>$conditions,
'order' => array('Office.description'),
'group' => 'Computer.id'
));
This can be written something like this :-
$joins = array(
array(
'table' => 'SELECT max(post_date) MaxPostDate, post_author FROM wp_posts WHERE post_status='publish' AND post_type='post'GROUP BY post_author',
'alias' => 'P2',
'type' => 'INNER',
'conditions' => array('WpPost.post_author = p2.post_author','WpPost.post_date = p2.MaxPostDate')
)
);
$conditions=array("WpPost.post_status='publish'","WpPost.post_type='post'");
$this->WpPost->find('all',array('fields'=>array('WpPost.*'),'joins'=>$joins,'conditions'=>$conditions);

CakePHP: adding DISTINCT to find causes an associated to get omitted

We build a fairly complex set of $conditions, then we search using Paginator:
$this->Paginator->settings = array( 'conditions'=>$conditions,
'joins'=>$joins,
'limit'=>25,
//'fields' => array('DISTINCT (User.id)')
);
$resume_display_array = $this->Paginator->paginate('User');
You'll see the 'fields' is commented out. When we uncomment that field, it causes associated model Resume to get dropped from the results array (without it, each result returned includes a [Resume] key.
Why is this happening?
Here's the SQL dump WITH the DISTINCT option in use:
SELECT DISTINCT (`User`.`id`), `User`.`id`
FROM `sw`.`users` AS `User`
LEFT JOIN `sw`.`taggings_users` AS `TaggingUser`
ON (`User`.`id`= `TaggingUser`.`user_id`)
LEFT JOIN `sw`.`taggings` AS `Tagging`
ON (`TaggingUser`.`tagging_id`= `Tagging`.`id`)
LEFT JOIN `sw`.`resumes` AS `Resume`
ON (`Resume`.`user_id` = `User`.`id`)
WHERE `User`.`first_name` LIKE '%jordan%' AND NOT (`Tagging`.`tag_name` = ('done'))
LIMIT 25
Here's the SQL dump WITHOUT the DISTINCT option:
SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified`, `User`.`email`, `User`.`wordpress_user_id`, `User`.`first_name`, `User`.`last_name`, `User`.`group_id`, `Resume`.`id`, `Resume`.`user_id`, `Resume`.`wordpress_resume_id`, `Resume`.`wordpress_user_id`, `Resume`.`has_file`, `Resume`.`is_stamped`, `Resume`.`is_active`, `Resume`.`file_extension`, `Resume`.`created`, `Resume`.`modified`, `Resume`.`is_deleted`
FROM `sw`.`users` AS `User`
LEFT JOIN `sw`.`taggings_users` AS `TaggingUser`
ON (`User`.`id`= `TaggingUser`.`user_id`)
LEFT JOIN `sw`.`taggings` AS `Tagging`
ON (`TaggingUser`.`tagging_id`= `Tagging`.`id`)
LEFT JOIN `sw`.`resumes` AS `Resume`
ON (`Resume`.`user_id` = `User`.`id`)
WHERE `User`.`first_name` LIKE '%jordan%' AND NOT (`Tagging`.`tag_name` = ('done'))
LIMIT 25
Update
Here is a var_dump of $joins:
array(
(int) 0 => array(
'table' => 'taggings_users',
'type' => 'LEFT',
'alias' => 'TaggingUser',
'conditions' => array(
(int) 0 => 'User.id= TaggingUser.user_id'
)
),
(int) 1 => array(
'table' => 'taggings',
'type' => 'LEFT',
'alias' => 'Tagging',
'conditions' => array(
(int) 0 => 'TaggingUser.tagging_id= Tagging.id'
)
)
)
If you specify the fields option, you need to specify all fields that you want to retrieve.
By setting it ONLY to User.id, you're telling it that that is the ONLY field you want returned.
You could also try something like below as a catchall (not sure if that works, but if not, you get the idea - you're limiting your own results):
'fields' => array('*', 'DISTINCT (User.id)')

Select 3 tables in zend

I'm a new in Zend.
In my model Default_Model_ApplicationMapper, I wanna use a db-table Application_Model_DbTable_Application to run a query like that
"Select * from application as a, category as c, user as u where a.user_id = u.id and a.category_id = c.id";
I tried this:
$table = new Application_Model_DbTable_Application();
$select = $table->select()->from(array('a' => 'application'))
->from(array('c' => 'category'))
->from(array('u' => 'user'))
->where('a.user_id = u.id and a.category_id = c.id');
Of course this thing does not work.
Can you help me with this?
Instead of using from(array('a' => 'table')) three times, try using from(array('a' => 'table1', 'b' => 'table2', 'c' => 'table3')).

Cakephp custom query with left join table rows as nested arrays

I'm trying to get nested arrays for my Cakephp custom query below:
$this->query("
SELECT *
FROM group_buys GroupBuy
LEFT JOIN products Product
ON Product.id = GroupBuy.product_id
LEFT JOIN group_buy_users GroupBuysUser
ON GroupBuysUser.group_buy_id = GroupBuy.id
LEFT JOIN group_buy_images GroupBuyImage
ON GroupBuyImage.group_buy_id = GroupBuy.id
LEFT JOIN product_details ProductDetail
ON ProductDetail.product_id = Product.id
LEFT JOIN specifications Specification
ON Specification.id = ProductDetail.specification_id
LEFT JOIN specification_categories SpecificationCategory
ON SpecificationCategory.id = Specification.specification_category_id
WHERE GroupBuy.id = {$id}
");
Problem with this is that it comes up with redundant data obviously with GroupBuy table row values repeating which I don't want.
Is there a way we can have nested arrays if LEFT JOINED table has more rows than the former table with Cake's custom query?
I know this can be done with find recursive = 2 but would like to achieve this with custom query.
Have you tried using containable?
$this->GroupBuy->Behaviors->attach('Containable');
$this->GroupBuy->find('all', array(
'conditions' => array('GroupBuy.id' => $id),
'contain' => array(
'Product' => array(
'ProductDetail' => array(
'Specification' => array(
'SpecificationCategory'
)
)
),
'GroupBuysUser',
'GroupBuyImage'
),
));

Cakephp joining tables via find option not working

I'm trying to join a Users table to my curent hasMany Through table which has Interest and User model id's.
Below is the find query with options:
$params = array(
'fields' => array('*', 'COUNT(DISTINCT(InterestsUser.interest_id)) as interest_count'),
'limit' => 15,
'recursive' => -1,
'offset' => $offset,
'conditions' => array('InterestsUser.interest_id' => $conditions),
'group' => array('InterestsUser.user_id'),
'order' => array('interest_count DESC', 'InterestsUser.user_id ASC', 'InterestsUser.interest_id ASC'),
'joins' => array(
array('table' => 'users',
'alias' => 'User',
'type' => 'LEFT',
'conditions' => array(
'User.id' => 'InterestsUser.user_id',
)
)
)
);
$results = $this->InterestsUser->find('all', $params);
This returns InterestsUser table fine but does not return any values for Users table. It only returns field names.
What could be wrong?
UPDATE:
OK, above is generating below SQL which I got from Cake's datasources sql log:
SELECT *, COUNT(DISTINCT(InterestsUser.interest_id)) as interest_count
FROM `interests_users` AS `InterestsUser`
LEFT JOIN users AS `User` ON (`User`.`id` = 'InterestsUser.user_id')
WHERE `InterestsUser`.`interest_id` IN (3, 2, 1)
GROUP BY `InterestsUser`.`user_id`
ORDER BY `interest_count` DESC, `InterestsUser`.`user_id` ASC, `InterestsUser`.`interest_id` ASC
LIMIT 15
Why is users table values returning NULL only for all fields?
UPDATE:
OK I tried below but this is working fine...What am I missing here!!??
SELECT * , COUNT( DISTINCT (
interests_users.interest_id
) ) AS interest_count
FROM interests_users
LEFT JOIN users ON ( users.id = interests_users.user_id )
WHERE interests_users.interest_id
IN ( 1, 2, 3 )
GROUP BY interests_users.user_id
ORDER BY interest_count DESC
LIMIT 15
The array syntax for join conditions should be like the following
array('User.id = InterestsUser.user_id')
as opposed to array('User.id' => 'InterestsUser.user_id'). For more, see http://book.cakephp.org/view/1047/Joining-tables.

Categories