We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.



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



125.8k
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.



5.1k

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