繁体   English   中英

CakePhp:查找使用包含条件

[英]CakePhp: Find using Contain with condition

我有以下型号:

  1. 公司(编号,名称)
  2. 员工(id,姓名,company_id,isRemoved)[公司有很多员工]

在指定的关联中,员工具有默认条件,即

public $hasMany = array(
      'Employee' => array(
        'className' => 'Employee',
        'foreignKey' => 'company_id',
        'dependent' => true,
        'conditions' => array(
          'Employee.isRemoved' => 0
        ),
      )
  );

关联具有默认条件,即不删除员工。 我正在对公司使用以下查找查询,以仅获取其名称与字符串匹配的那些雇员:

$this->Company->find('all', array(
    'contain' => array(
        'Employee' => array(
            'conditions' => array(
                'Employee.name LIKE' => '%'.$search_text.'%')
            ),
            'fields' => array('Employee.id, Employee.name')
        )
    )
));

我面临的问题是,当我在contains中使用条件时,将不应用关联中指定的默认条件,而当未指定条件键时,将应用关联中指定的默认条件。

这是Cakephp的默认行为吗?如何进行? 我正在使用Cakephp 2.8.4

我无法告诉您被覆盖的模型中的条件是否是CakePHP的默认行为。 不过,我可以为您提供一个替代方案:

通过在模型中使用beforeFind()回调,您可以添加'Employee.isRemoved' => 0条件。

因此,在您的Company模型中,您可以执行以下操作:

function beforeFind(array $queryData) {
    if(isset($queryData['contain']['Employee'])) {
        //Notice the extra [] to not overwrite the conditions set in the controller
        $queryData['contain']['Employee']['conditions'][]['Employee.isRemoved'] = 0;
    }
    return $queryData;
}

免责声明:我没有测试此代码。

资料来源: https : //stackoverflow.com/a/17544106/6786476

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM