Question

I have a condition on which most of my models will have to adhere when retrieving data.

This condition will be the id of the company to which the user logged in. So for instance, let's say the company id is 1, then all the information relating to company_id 1 must show.

How can I set a default condition to my models?

Was it helpful?

Solution

Check this code

class FooModel extends AppModel {

    protected $_companyId = null;

    public function setCompanyId($companyId) {
        // Optional validation of the id here
        $this->_companyId = $companyId;
    }

    public function beforeFind($query) {
        if (!empty($this->_companyId)) {
            $query['conditions'][$this->alias . '.company_id'] = $this->_companyId;
        }
        return $query;
    }
}

To decouple it from the models I would suggest you to implement these two methods in a behavior and attach it to only the models that need it.

Edit, here as behavior:

class CompanyFilterBehavior extends ModelBehavior {

    protected $_companyId = null;

    public function setCompanyId(Model $Model, $companyId) {
        // Optional validation of the id here
        $this->_companyId = $companyId;
    }

    public function beforeFind(Model $Model, $query) {
        if (!empty($this->_companyId)) {
            $query['conditions'][$Model->alias . '.company_id'] = $this->_companyId;
        }
        return $query;
    }
}

In your AppController you can do this:

public function beforeFilter() {
    if ($this->User->loggedIn() 
        && $this->{$this->modelClass}->Behaviors->loaded('CompanyFilter'))
    {
        $this->{$this->modelClass}->setCompanyId($this->Auth->user('company_id'));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top