tags:

views:

31

answers:

2

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 get 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.

A: 

This should do the trick:

$products = $this->Product->find('all', array(
    'conditions' => array(
        'User.id' => $user_id_from_session
    )
));
Splashdust
it's a many to many relation.. User.id is not a field in the Products table... the query is giving me error cause it's not referencing the Products_Users table at all
NachoF
+1  A: 

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
 */
deceze
but how do i get the data to the view?? I need to view data to be populated with a bunch of products related to the user thats logged in... rememebr I am trying to do this in products/index
NachoF
@NachoF It seems you're missing the fundamentals of Cake. Please follow [the tutorial](http://book.cakephp.org/view/1535/Create-a-Posts-Controller) until you understand the basic Model->Controller->View flow.
deceze
@Nacho Try to `bake` all your views (I think you have done this already). Look at the `/users/view/` controller and views. It essentially does what you want. Once you understand how it works it should be easy to adapt to your needs.
deceze