cakephp 加入和 mysql 加入

cakephp join and mysql join

已更新!

我是 cakephp 的新手,但对 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 

蛋糕php

$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() 或连接中获取数据):

//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'
            )
        )
    )
));