【问题标题】:cakephp join and mysql joincakephp 加入和 mysql 加入
【发布时间】:2015-03-22 15:13:39
【问题描述】:

更新!

我在 cakephp 方面相对较新,但对 mysql 和 php 有经验。 模型如下:

Person->Father

父亲自称人。

我根据返回“1”人的父亲的mysql查询写了以下内容 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=....,但现在似乎子查询并且看起来连接不起作用)因为父亲和人不是相同的型号,如果我有

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

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

【问题讨论】:

  • 什么是 $this->find('first', $options);?你的意思是 $this->Person->find('first', $options); ?你在哪里有这个代码?在哪个控制器,模型等中。
  • 是的,很抱歉它不正确,你是对的。代码在控制器中。

标签: php mysql cakephp join


【解决方案1】:

试试这个。 (请注意缺少包含。使用包含的唯一原因是您尚未在主模型的 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'
            )
        )
    )
));

【讨论】:

  • 我加入是因为我想获取“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['Father']['name'] 或 $ask['Father']['id'] 但我需要在 Person 模型上工作。 $ask['Person']['name'] 这会给我一个错误 no index 'name' 因此我需要“转换(它不是真正的转换)” $fatherquery=$this->Person->find(' first',array('conditions'=>array('Person.id'=>$ask['Father']['id'])));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多