CakePHP LEFT JOIN在具有条件的多个表上

时间:2013-08-08 01:01:26

标签: mysql cakephp left-join

我想使用这个CakePHP表单进行LEFT连接。见CakePHP Book - section on Joining Tables

$options['joins'] = array(
    array('table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);
$Item->find('all', $options);

除了我的LEFT JOIN有一个带有条件的从属表。在MySQL中,连接看起来像这样

LEFT JOIN (
    channels as Channel 
        INNER JOIN regions as Region ON ( Region.id = Channel.region_id and Region.id=1 )
) ON Channel.id = Item.channel_id

我可以使用$options['joins']语法在CakePHP 2.0中执行相同的操作吗?

3 个答案:

答案 0 :(得分:1)

因此,经过一番摆弄,我发现这是CakePHP中的“技巧”。根据SQL EXPLAIN,这是一个比使用子查询强制LEFT连接表上的条件快得多的连接

$options['joins'] = array(
    array('table' => '(channels as `Channel` INNER JOIN regions as `Region`
                      ON ( `Region`.id = `Channel`.region_id and `Region`.id=1 ))',
//        'alias' => 'Channel',  // the alias is 'included' in the 'table' field
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);
$Item->find('all', $options);

答案 1 :(得分:1)

$options['joins'] = array(
array('table' => 'channels',
    'alias' => 'Channel',
    'type' => 'LEFT',
    'conditions' => array(
        'Channel.id = Item.channel_id',
        'Region.id' = 1

    )
  )
);
$Item->find('all', $options);

连接选项中的条件键也可以正常工作

答案 2 :(得分:1)

有点晚了但是对于那些会像我一样通过谷歌看到这一点的人,你应该尝试以下方法。

$options['joins'] = array(
    array(
        'table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Item.channel_id = Channel.id'
        )
    ),
    array(
        'table' => 'regions',
        'alias' => 'Region',
        'type' => 'INNER',
        'conditions' => array(
            'Channel.region_id = Region.id',
            'Region.id = 1'
        )
    )
);