开发者

CakePHP get matches in an array() based on hasMany relationship

PlanDetails hasMany Companies. PlanDetail table has company_id field.

This is all I need to achieve: PlanDetail.company_id = Company.id. So get all Plan Details where PlanDetail.company_id matches Company.id.

Here is the query I have bee开发者_开发知识库n messing with in the plan_details_controller:

function pd_list_by_company() {
    $this->PlanDetail->unbindModel(array('hasMany' => array('Plan')));
    $comp_id = $this->PlanDetail->Company->find('all');
    $result = $this->PlanDetails->find('all', array('conditions' => array
('Company.id' => 'PlanDetail.company_id')));
    $company_id = $this->PlanDetail->read('company_id');
    }

I cannot just get the results I need.. what am I doing wrong here?


Sounds like a simple condition on the company_id field to me:

$this->PlanDetail->find('all', array('conditions' => array('company_id' => $company_id)))

Or, if you want the company as well and your associations are hooked up correctly:

$company = $this->Company->read(null, $company_id);

// echo $company['Company']
// echo $company['PlanDetail'][0], $company['PlanDetail'][1] etc...

You need to get a $company_id to query on from somewhere, which is usually the URL:

public function pd_list_by_company($company_id)

Then visit this action with the URL /plan_details/pd_list_by_company/42, which can be linked to using $this->Html->link('foobar', array('controller' => 'plan_details', 'action' => 'pd_list_by_company', 42)).

Complete example:

public function view($planId) {
    $plan = $this->PlanDetail->read(null, $planId);
    if (!$plan) {
       $this->cakeError('error404');
    }
    $otherPlansBySameCompany = $this->PlanDetail->find('all', array(
        'conditions' => array('company_id' => $plan['PlanDetail']['company_id'])
    ));
    $this->set(compact('plan', 'otherPlansBySameCompany'));
}


I am displaying the set() find result in the Plan Detail view.ctp.

This is how I solved it:

    function view($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid plan detail', true));
        $this->redirect(array('action' => 'index'));
    }
    $this->set('planDetail', $this->PlanDetail->read(null, $id));
        $cid = $this->PlanDetail->read('Company.id');
        $cid_extract = Set::extract($cid, 'Company.id');
    $this->set('planComps', $this->PlanDetail->find('all',array('conditions' => array("company_id" => $cid_extract))));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜