设置默认模型条件 [英] Setting default model conditions

查看:77
本文介绍了设置默认模型条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个条件,我的大多数模型将检索数据时必须遵守。

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

此条件将是用户登录的公司的ID因此,例如,假设公司ID为1,那么所有与company_id 1相关的信息都必须显示。

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?

推荐答案

检查此代码

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.

编辑,这里作为行为: / strong>

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



在您的AppController中,您可以这样做:

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

这篇关于设置默认模型条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆