cakephp连接和mysql连接


cakephp join and mysql join

更新!

我对cakepp还是个新手,但对mysql和php有经验。模型看起来像:

Person->Father

父亲是自我指代的人。

我根据mysql查询写了以下内容,该查询返回了"1"个人的父亲mysql:

SELECT `Father`.name,`Father`.id from persons as `Father` left join persons as `Person` on `Person`.`father_id`=`Father`.`id` where `Person`.id=1 

结块

$options = array(
'fields' => array(
    //'Father.name',
    'Father.id',
),
'joins' => array(
    array(
        'conditions' => array(
            'Person.father_id = Father.id',
        ),
        'table' => 'persons',
//          'alias' => 'Person', i commented because having conflict with scaffolded model
            'type' => 'left',
        ),
    ),
    'conditions' => array(
        'Person.id' => '1',
    ),
    'contain' => array(
        'Person','Father',
    ),
);
$data = $this->Person->find('first', $options);
$fatherquery=$this->Person->find('first',array('conditions'=>array('Person.id'=>$data['Father']['id'])));

为了获得与mysql相同的结果,我添加了这一行(最后一行$father=…,但现在它似乎是子查询,看起来连接不起作用),因为father和Person不是同一个模型,如果我有

$data['Father']['name'] and $data['Person']['name'] they are not equal

顺便说一句,我已经有了解决方案,但也许我误解了一些概念。有没有办法让mysql查询更容易?

试试这个。(请注意缺少contain。使用contain的唯一原因是,如果您还没有在主模型的find()或join中获得数据):

//Person model (cake 2.x code)
$this->find('first', array(
    'fields' => array(
        'Father.id',
        'Father.name'
    ),
    'conditions' => array(
        'Person.id' => 1
    ),
    'joins' => array(
        array(
            'table' => 'persons',
            'alias' => 'Father',
            'type' => 'left',
            'conditions' => array(
                'Person.father_id = Father.id'
            )
        )
    )
));