Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP and subquery

Tags:

sql

cakephp

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
like image 391
BAD_SEED Avatar asked Apr 24 '11 10:04

BAD_SEED


1 Answers

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
                )

        )

)
like image 139
Chuck Burgess Avatar answered Nov 15 '22 07:11

Chuck Burgess