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条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?