开发者

CakePHP Relationship Question

开发者 https://www.devze.com 2022-12-19 05:24 出处:网络
I am trying to configure CakePHP to act as a REST API for an app i\'m writing. I have 3 tables: dishes {

I am trying to configure CakePHP to act as a REST API for an app i'm writing.

I have 3 tables:

dishes {
 id,
 name,
 description
}

users {
 id,
 name,
 email
}

dishes_users {
 id,
 user_id,
 dish_id
}

I would like it so that when someone visits /users/1.xml, the data that gets returns is just the list of 'dishes' that a user has in the 'dishes_users' table, i dont want anything from users or dishes_users to be in there, just the id, name, and description of the dishes table.

in the end the xml structure has to be:

<dishes>
 <dish id="1" name="whatever" description ="This is a description"/>
 <dish id="2" name="whatever" description="This is another description"/>
</dishes>

This is currently the relationship i am using in the users model:

var $hasAndBelongsToMany = array(
    "Dish" => array(
        'className' => 'Dish',
        'joinTable' => 'dishes_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'dish_id',
        'unique'                 => true,
        'conditions'             => '',
        'fields'                 => '',
        'order'                  => '',
        'limit'                  => '',
        'offset'                 => '',
        'finderQuery'            => '',
        'deleteQuery'            => '',
        'insertQuery'            => ''
));

In the controller i have:

function view($id) {
    $dishes = $this->User->findAllById($id);
    $this->set(compact('beers'));
}

This gives me what i want, but it also gives me a lot of stuff i don't want. All i need is the list of dishes.

Tha开发者_如何学Cnks for any help, this has been driving me nuts.


Try limiting the scope a bit. You don't mention the controller you're doing this work in, but it looks like it isn't the DishesController. If, for example, it's the UsersController:

$dishes = $this->User->Dish->find( 
  'all', 
  array(
    'fields'     => array( 'Dishes.*' ),
    'conditions' => array( 'DishesUsers.user_id' => $this->id ) // where $this is a user
  )
);

This should, from the UsersController, pull only dish data that's related to a given user. I kind of rattled that off from memory, but it may get you somewhere in the neighborhood of what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消