fetch only 'enabled' records from the database in cakephp v1.3

落花浮王杯 提交于 2019-12-12 05:33:47

问题


Is there any way of fetching only those records of a model which have 'status = 1' in cakephp v1.3 ?

I have created a field named 'status' in every table of my web application.

I have a model named 'Message'. What I want is that only those messages are displayed, included in search results which have 'status = 1'. Messages with a 'status = 0' won't be displayed and won't be included in search results too.

Please help me if I can do it the cakePHP way, for now as a temporary solution I am using the 'status = 1' in the conditions array of every find of messages.

Thanks


回答1:


I'd include this in the beforeFind() callback method. You can include it in the callback for every model (but only once for each model--not for each query) or you can apply it to your AppModel so that all of your other models inherit it.

In the beforeFind() callback, you can modify the structure of the query. In this case, you'd apply the condition array( 'status' => 1 ) to your incoming query. Dump the argument data structure to see what's coming in and I think it will make sense to you.

Note that if you chose to do this in your AppModel and have to create a model-specific beforeFind callback in the future, you'll need to be sure that you call parent::beforeFind() in your subclass' beforeFind() method.




回答2:


Found the answer over here The beforeFind() callback comes handy for this.

like this

public function beforeFind($conditions) {
    if(!isset($conditions['conditions']['Message.status']) && !isset($conditions['conditions']['status'])) {
        $conditions['conditions']['Message.status'] = 1;
    }
    return $conditions;
}



回答3:


Basically you are speaking for Soft deletable behavior. There is one here For me it's not perfect, but for simple app it could do the job. In the comments you can see the improvements too :)

But extending the beforeFind() in the AppModel should be ok too.



来源:https://stackoverflow.com/questions/3138389/fetch-only-enabled-records-from-the-database-in-cakephp-v1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!