Setting default model conditions

后端 未结 1 483
南方客
南方客 2021-01-15 08:52

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

相关标签:
1条回答
  • 2021-01-15 09:10

    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'));
        }
    }
    
    0 讨论(0)
提交回复
热议问题