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

Hello

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 ?

thanks

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



3.0k
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



53.4k
Accepted
answer
edited Jun '17

Something like this should work:

<?php
$AgencyCustomers = Customers::find();
?>
<?php
class Customers{

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

        if(isset($criteria['bind'])){
            $criteria['bind']['agency'] => $loggedInUserAgencyID;
        }
        else{
            $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.



3.0k

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")