Nicholas Jephcott Nicholas Jephcott - 5 months ago 17
AngularJS Question

Cakephp control when model associations are pulled

I have inherited a project that is using Cakephp 2.0 and Angular for various things and I was looking up how to do joins and and Model associations.

I have a model that has associations to the users table like so

App::uses('AppModel', 'Model');

class Booking extends AppModel {

public $belongsTo = array(
'Trainer' => array(
'className' => 'User',
'foreignKey' => 'to_user'
),
'Participant' => array(
'className' => 'User',
'foreignKey' => 'user'
)
);

}


This works. However I have concerns about speed and security of always getting all the user table every time you access a booking. Much of the data is passed to angular and then displayed via javascript and I have found a few places were the program is passing the results of model searches directly to angular then letting it handle disseminating that data. I worry that if I add in these associations then somewhere I may now be passing out my user table into javascript which would include sensitive data.

I am wondering if it is possible to add associations at runtime via using a function call. eg.

App::uses('AppModel', 'Model');

class Booking extends AppModel {

public function getUserInfo(){
$this->$belongsTo = array(
'Trainer' => array(
'className' => 'User',
'foreignKey' => 'to_user'
),
'Participant' => array(
'className' => 'User',
'foreignKey' => 'user'
)
);
}

}


Then in a controller use:

$this->loadModel("Booking");
$this->Booking->getUserInfo();


This is aimed so you have control over whether the associated tables are being pulled as well.

Answer

You can Create Associations on the Fly as follows,

App::uses('AppModel', 'Model');

class Booking extends AppModel {

    public function getUserInfo(){
    $this->bindModel(
        array('belongsTo' => array(
                'Trainer' => array(
                    'className' => 'User',
                'foreignKey' => 'to_user')),
            'Participant'=> array(
                'className' => 'User',
                    'foreignKey' => 'user' ) )
            );
    return $this->find('all');

    }
}
Comments