Manish M Demblani
Manish M Demblani

Reputation: 910

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

Upvotes: 0

Views: 1253

Answers (1)

FrankSunnyman
FrankSunnyman

Reputation: 241

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

Upvotes: 1

Related Questions