help filtering data in cakephp
Im new to cakephp and Im having a little problem querying data. I have a User model and a Product model in a many to many relation.
What I what is simply for my Products/Index action to only ge开发者_StackOverflow中文版t the products associated to that User (the user is stored in session) and not all Products (which is what it does by default).
Please help.
You only need to set up the relationship properly, the rest is automatic.
Model:
class User extends AppModel {
var $hasAndBelongsToMany = array(
'Product' => array( /* set up relationship */ )
);
}
Controller:
$this->User->recursive = 2; // just to make sure, shouldn't be necessary
$user = $this->User->read(null, $userId);
debug($user);
/**
* $user['User'] contains the user data
* $user['Product'] contains associated products
*/
This should do the trick:
$products = $this->Product->find('all', array(
'conditions' => array(
'User.id' => $user_id_from_session
)
));
精彩评论