简体   繁体   中英

CakePhp: Find using Contain with condition

I have the following models:

  1. Company(id, name)
  2. Employee(id, name, company_id, isRemoved) [Company has many Employees]

In the association specified, the employee has a default condition, that

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

The association has a default condition of an employee being not removed. I am using the following Find Query on company to get only those employees whose name matches a string:

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

The problem I am facing is that, When I use conditions within contain, the default condition specified in the association is not applied and when the conditions key is not specified, the default condition specified in the association is applied.

Is this a default behaviour of Cakephp and How to proceed about it? I am using Cakephp 2.8.4

I can not tell you if the conditions in the model being overwritten is default behaviour of CakePHP. I can however offer you a possible alternative:

By using the beforeFind() callback in your model you could add your 'Employee.isRemoved' => 0 condition.

So in your Company model you could do something like:

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;
}

Disclaimer: I did not test this code.

Source: https://stackoverflow.com/a/17544106/6786476

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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