CakePHP: Is there a way to include variables in the definition of hasAndBelongsToMany?
I recently started using CakePHP and am trying to define User-specific "field" preferences. Basically, I want each user to be able to specify which fields he/she wants to see in a table.
To do this, I have a users table, a fields table, and a fields_users table. The last table is just a field_id and user_id, so the code knows to link that field with that user.
So far, I have created a controller/model for 'User' and a controller/model for 'Fields', and am linking them with the hasAndBelongsToMany property. For instance, in the 'Field' model, I have the following property defined:
` var $hasAndBelongsToMany = array (
'User' => array (
'className' => 'User',
'foreign_key' => 'field_id',
'join_table' => 'fields_users',
'fields' => array( 'User.id' ),
'conditions' => array( 'User.id' => 2 ),
'unique' => false,
) );`
As you can see above, the 'User.id' in the 'conditions' part of the array is hard-coded.
My question is this: How can I make it so that the 'conditions' part of this property is set to be the current user's id?
Obviously, I only care about the current user's field preferences, but at the moment I'm getting everyone's user info.
Setting it to be a variable in the initial property definition doesn't work, and I'm not sure at what point I should be doing this (or if there's a better way entirely). (doin开发者_开发知识库g it in beforeFilter didn't work, and I can't seem to access $_SESSION from the model's __construct function)
Do it from the controller. You can get the current user id by $this->Auth->user('id')
.
精彩评论