我想使用这个 CakePHP 表单进行左连接。参见 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 中做同样的事情吗?
最佳答案
所以经过一些摆弄之后,我发现这在 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);
关于mysql - CakePHP LEFT JOIN 在有条件的多个表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18116290/