cakephp:如何为左连接制定条件

时间:2014-06-30 14:53:03

标签: cakephp join outer-join

我有两个实体:谱号和具有n-n关联的批次。所以我定义了三个模型:Clefs,lot和ClefLots:

class ClefLots extends AppModel {
    var $specific = true;
    public $name = 'ClefLots';

    public $belongsTo = array(
        'Clefs' => array(
            'className' => 'Clef',
            'foreignKey' => 'clefs_id'
        ),
        'Lots' => array(
            'className' => 'Lot',
            'foreignKey' => 'lots_id'
        )   
    );
}

现在我需要列出一个给定的谱号,哪个谱号与谱号无关。 此查询有效:

SELECT
    `Lot`.`id`, `Lot`.`title`, `ClefLots`.`clefs_id`, `ClefLots`.`lots_id` 
FROM
    `dunkerque52`.`lots` AS `Lot` 
    LEFT JOIN
        `dunkerque52`.`clef_lots` AS `ClefLots`
            ON (((`ClefLots`.`clefs_id` = '539c1896-1cc0-48ac-a2d6-2c9e5b79c62b')
            AND (`ClefLots`.`lots_id` = Lot.id))) 
WHERE
    `ClefLots`.`lots_id` IS NULL

使用cakephp,此代码失败:

$this->loadModel('ClefLots');
$conditions = array(
    'fields' => array(
        'Lot.id', 'Lot.title', 'ClefLots.clefs_id', 'ClefLots.lots_id'
    ),
    'joins' => array(
        array(
            'table' => 'clef_lots',
            'alias' => 'ClefLots',
            'type' => 'left',
            'conditions' => array(
                array(
                    'ClefLots.clefs_id' => $id,
                    'ClefLots.lots_id => Lot.id'
                )
            ),
        ),
    ),
    'conditions' => array(
        "ClefLots.lots_id" => null,
    )
);
$lots = $this->Lot->find('list',$conditions);    

并且该代码不正确:

$this->loadModel('ClefLots');
$conditions = array(
    'fields' => array(
        'Lot.id', 'Lot.title', 'ClefLots.clefs_id', 'ClefLots.lots_id'
    ),
    'joins' => array(
        array(
            'table' => 'clef_lots',
            'alias' => 'ClefLots',
            'type' => 'left',
            'conditions' => array(
                array(
                    'ClefLots.clefs_id' => $id,
                    'ClefLots.lots_id' => 'Lot.id'
                )
            ),
        ),
    ),
    'conditions' => array(
        "ClefLots.lots_id" => null,
    )
);
$lots = $this->Lot->find('list',$conditions);   

所以我的问题是:如何在左连接中指定条件以获得正确的查询?

1 个答案:

答案 0 :(得分:0)

您的conditions数组不正确,它不应包含嵌套数组,SQL片段应作为字符串传递。

同样在你的SQL片段中>之后的=不应该存在。

这是连接条件应该是这样的:

'conditions' => array(
    'ClefLots.clefs_id' => $id,
    'ClefLots.lots_id = Lot.id'
)