cakephp连接和mysql连接

cakephp连接和mysql连接,php,mysql,cakephp,join,Php,Mysql,Cakephp,Join,更新 我对cakephp比较陌生,但对mysql和php有经验。 模型如下所示: Person->Father 父亲是自我指代的人 我基于mysql查询写了以下内容,它返回了“1”人的父亲 mysql: cakephp $options = array( 'fields' => array( //'Father.name', 'Father.id', ), 'joins' => array( array( 'conditions' =

更新

我对cakephp比较陌生,但对mysql和php有经验。 模型如下所示:

Person->Father
父亲是自我指代的人

我基于mysql查询写了以下内容,它返回了“1”人的父亲 mysql:

cakephp

$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查询更简单?

试试这个。(请注意,缺少包含。使用包含的唯一原因是如果您尚未在主模型的find()或join中获取数据):


什么是$this->find('first',$options);?你是说$this->Person->find('first',$options)?你在哪里有这个代码?是的,对不起,它不正确,你是对的。代码在控制器中。我加入是因为我想获取“Person1”父亲的详细信息抱歉,我犯了一个小错误:$this->Person->find Dave您的查找将返回Person1的详细信息,而不是他父亲的更新答案。我还没有测试,但我看到的唯一潜在问题是,为了成功运行联接,您可能还需要在字段数组中包含“Person.id”字段。我想你不会,但如果它出错了,试试看。是的,你做的几乎一样。正如我在上面写的:$data['Father']['name']和$data['Person']['name']在我的情况下是不平等的。我必须和Person而不是父亲一起工作。我通过以下方式转换它们:$father=$object->find('first',array('conditions'=>array('Person.id'=>$data['father']['id']));但这是两步。有没有办法一步到位呢?我相信我明白你的意思,并且相信我的答案是正确的。是的,你的答案是正确的。假设您将其保存到变量$ask。现在您可以使用$ask['DAVER']['name']或$ask['DAVER']['id']但我需要处理个人模型$ask['Person']['name']这会给我一个错误,没有索引'name',因此我需要“转换(不是真正的转换)”$fatherquery=$this->Person->find('first',array('conditions'=>array('Person.id'=>$ask['Father']['id']);
$data['Father']['name'] and $data['Person']['name'] they are not equal
//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'
            )
        )
    )
));