How can I write a SQL subquery using cake syntax? I know how to code a simple query, but I can't handle subqueries.
This is the original query:
SELECT Assumption.id, Referee.id, Referee.first_name, Referee.second_name
FROM referees AS Referee
INNER JOIN (
SELECT a.id, a.referee_id
FROM assumptions a
WHERE a.season_id =7
) AS Assumption ON Referee.id = Assumption.referee_id
Since you didn't understand the syntax, this is the actual query:
$records = $this->Referee->find('all', array(
'fields' => array(
'Assumption.id', 'Referee.id', 'Referee.first_name', 'Referee.second_name'
),
'joins' => array(
array(
'table' => 'assumptions',
'alias' => 'Assumption',
'type' => 'INNER',
'foreignKey' => false,
'conditions' => array('Referee.id = Assumption.referee_id', 'Assumption.season_id = 7'),
),
),
)
);
Which produces this query:
SELECT
`Assumption`.`id`,
`Referee`.`id`,
`Referee`.`first_name`,
`Referee`.`second_name`
FROM `referees` AS `Referee`
INNER JOIN assumptions AS `Assumption`
ON (`Referee`.`id` = `Assumption`.`referee_id`
AND `Assumption`.`season_id` = 7)
Which provide the results you are looking for.
Sample output:
Array
(
[0] => Array
(
[Assumption] => Array
(
[id] => 1
[0] => Array
(
[id] => 1
[season_id] => 7
[referee_id] => 1
[name] => SomeAssumpton
)
)
[Referee] => Array
(
[id] => 1
[first_name] => Ref
[second_name] => one
)
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With