Cakephp复杂关系查找

时间:2010-10-28 21:08:19

标签: php cakephp mysql cakephp-1.3

我有一个复杂的数据库模型,我无法正确查找

user(id,name ...)

1 Harsha

2 Jasmine

模块(id,name)

1 Users

2 Restaurants

3 Dishes

restaurant(id,name ....)

1 KFC 

2 Pizza Hut

菜肴(id,name,restaurant_id ..)

1 Cheese Pizza 2

项目(id,module_id,item_id)

1 1 1 (refers to User Harsha)

2 2 1 (Refers to KFC)

3 2 2 (Refers to Pizza Hut)

4 1 2 (Refers to User Jasmine)

5 3 1 (Refers to Cheese Pizza)

评论(id,parent_id,message,item_id,commenters_id)

1 0 "I love the ambience of Pizza Hut" 3 1 (Refers to Harsha reviewing Pizza Hut)

2 1 "You remind me of that kid in the next table who freaked me out." 3 2 (Refers to Jasmine Replying to Harsha's review on Pizza Hut)

3 0 "I love Cheese Pizza in Pizza Hut" 5 1 (Refers to the Cheese Pizza Review by Harsha)

我正在努力寻找所有餐厅的Harsha所做的评论,但我不能仅限于餐厅评论。我也回来了菜评论

这是我用过的代码         //检查用户是否已登录,如果是,则收集ID         $ id = $ this-> _loggedIN();

    // Find the ItemID from the Item Table
    $itemId = $this->User->Item->itemId('1', $id);

    // Finding the User Data and last Status Message
    $user = $this->User->Item->find('first', array('conditions' => array('Item.id' => $itemId), 'contain' => array('User', 'StatusMessage' => array('limit' => 1, 'order' => 'StatusMessage.created DESC'))));

    // Find the Restaurant Reviews of the Current User
    $reviews = $this->User->Item->Review->find('all', array('conditions' => array('Review.commenters_item_id' => $itemId, 'Review.pid = 0'), 'order' => array('Review.created DESC'), 
    'contain' => array(
        'Item' => array(
            'User' => array(
                'fields' => array('id', 'first_name', 'last_name', 'username', 'file')), 
            'Restaurant' => array('fields' => array('id', 'name', 'slug', 'file', 'area_id', 'city_id'), 
                'Area')), 
        'ReviewReply' => array(
            'Item' => array(
                'User' => array(
                    'fields' => array('id', 'first_name', 'last_name', 'username', 'file')))))));

1 个答案:

答案 0 :(得分:1)

    // I find it clearer to do the contain like this

    $this->Review->contain(array('Item','Item.User','Item.Restaurant', 'ReviewReply' etc...  ));  

    // Again I find it clearer this way as it avoids long lines and deeply indented arrays.

    $conditions = array(
        'Review.commenters_item_id' => $itemId, 
        'Review.pid' => 0, // should this be parent_id?
        'Item.module_id' => 2
        );
    $this->Review->find('all', array('conditions' => $conditions, 'order'=> 
    //...
    //etc.