PlanDetails有很多公司。 PlanDetail表有company_id字段。
这就是我需要实现的目标:PlanDetail.company_id = Company.id。因此,请获取PlanDetail.company_id与Company.id匹配的所有计划详细信息。
这是我在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');
}
我不能只得到我需要的结果..我在这里做错了什么?
答案 0 :(得分:2)
对company_id
字段来说,这听起来像一个简单的条件:
$this->PlanDetail->find('all', array('conditions' => array('company_id' => $company_id)))
或者,如果您也想要公司,并且您的关联正确连接:
$company = $this->Company->read(null, $company_id);
// echo $company['Company']
// echo $company['PlanDetail'][0], $company['PlanDetail'][1] etc...
您需要从某个地方获取$company_id
来查询,通常是网址:
public function pd_list_by_company($company_id)
然后使用网址/plan_details/pd_list_by_company/42
访问此操作,该网址可以链接到使用$this->Html->link('foobar', array('controller' => 'plan_details', 'action' => 'pd_list_by_company', 42))
。
完整示例:
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 :(得分:0)
我在Plan Detail view.ctp。
中显示set()查找结果这就是我解决它的方法:
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))));
}