dongyinglan8707 2011-05-25 00:36
浏览 17
已采纳

CakePHP基于hasMany关系在array()中获取匹配项

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 been 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?

  • 写回答

2条回答 默认 最新

  • dongxixian7803 2011-05-25 05:07
    关注

    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'));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改