Friday, January 14, 2022

[FIXED] Filter all find queries on entity CakePHP 3.6

Issue

let's say that I have an articles database and I want to only display articles that are published on the site (where published = 1). Instead of adding the condition in every find queries like the following:

$articles = $this->Articles->find('all')->where(['published' => 1]);

Is there a way that I can automatically apply this condition on all the find queries in the whole application at one place? If so how?


Solution

You can use beforeFind. This will be fired before every find query on your Article Model. Here is the documentation

Here is how to use it

public function beforeFind($event, $query, $options, $primary)
{

    $query->where(['article.visible' => 1]);

    return $query;
}


Answered By - ascsoftw

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.