Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

add find criteria in model


For my application my users can only see clients of their agency.

  • the logged user is attached to an agency
  • An agency has, several customers

i can do it in each actions in controller but if possible I would like to do it once in the model

What is the best way dto to this ?


By overriding find/findFirst methods i guess. But keep in mind that using query builder you would still need to make proper conditions.

edited Jun '17

thanks can i call the native find / findFirst methods after add criterias ?

also i see event beforeQuery it's possible to modify SQLStatement ?

Edit :

I found this tread

I think I can adapt it for my needs

edited Jun '17

Something like this should work:

$AgencyCustomers = Customers::find();
class Customers{

    function find($criteria = ['conditions'=>'']){
        $loggedInUserAgencyID = $_SESSION['agency_id'];
            $criteria['conditions'] .= ' AND agency = :agency:';
            $criteria['conditions'] = 'agency = :agency:';

            $criteria['bind']['agency'] => $loggedInUserAgencyID;
            $criteria['bind'] = ['agency'=>$loggedInUserAgencyID];

        return parent::find($criteria);

This assumes you're storing the user's agency id in $_SESSION. I'd recommend this because otherwise you'll have to do a query to find the user's agency id, each time you query for Customers. The agency ID doesn't change, so you might as well just look it up once and store it.


Thanks Dylan

Yes i store the user agency in $di->session and some others trifles as the user language, the user function ....

I try to realize a whole CRUD system of authorization according to the functions of the user and his agency

edited Jun '17

Well dont access $_SESSION use $di->get("session")