views:

26

answers:

3

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

A: 

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;
}
Gaurav Sharma
+1  A: 

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.

Rob Wilkerson
the main problem of this method is that when I am using $this->paginate['Message'] for showing up my messages in the index action then I again have to again write the condition "Message.status = '1' " :-(cakephp guys should include this functionality in upcoming version.
Gaurav Sharma
A: 

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.

Nik