AshHimself
AshHimself

Reputation: 4132

Filter data based on User field cakePHP

So I have a company based system and I am keeping all data within the one database and I separate the data by using a site_id field which is present in all tables and in the users table.

Now at the moment I am doing a condition on every single find('all'). Is there a more global way to do this. Maybe in the AppController? Even for saving data I am having to set the site_id every single save.

Something like

public function beforeFilter() {

    parent::beforeFilter();
    $this->set('site_id', $this->Auth->user('site_id'));

}

Any direction would only help. Thanks

Upvotes: 0

Views: 347

Answers (1)

Dave
Dave

Reputation: 29141

TLDR:

Create a Behavior with a beforeFind() method that appends a site_id condition to all queries.

Example/Details:

Create a behavior something along the lines of the below. Note, I'm getting the siteId from a Configure variable, but feel free to get that however you want.

<?php
class SiteSpecificBehavior extends ModelBehavior {

    public function setup(Model $Model, $settings = array()) {
        $Model->siteId = Configure::read('Site.current.id');
    }

    public function beforeFind(Model $Model, $query = array()) {
        $siteId = $Model->siteId;
        $query['conditions'][$Model->alias . '.site_id'] = $siteId ;
        return $query;
    }
}

Then on any/all models where you want to make sure it's site-specific, add:

public $actsAs = array('SiteSpecific');

This can be tweaked and improved up certainly, but it should give you a good idea.

Upvotes: 4

Related Questions