CakePHP pagination with HABTM models

前端 未结 3 1645
眼角桃花
眼角桃花 2020-12-11 09:31

I\'m having some problems with creating pagination with a HABTM relationship. First, the tables and relationships:

requests (id, to_location_id, from_locatio         


        
相关标签:
3条回答
  • 2020-12-11 10:02

    I've been able to get it working somewhat, but the solution doesn't feel very cakey at all.

    $items = $this->paginate(
        $this->Request->ToLocation->Item,
        array(
            "Item.id IN ("
            . "SELECT item_id FROM items_locations "
            . "WHERE location_id = " . $locationId
            . ")"
        )
    );
    
    0 讨论(0)
  • 2020-12-11 10:11

    To paginate HABTM, you need to temporarily bind 'hasOne' join model to model which you paginate:

    // prepare to paginate Item
    $this->Item->bindModel(array('hasOne'=>array('ItemsLocation')));
    $contain['ItemsLocation']=array();
    $conditions[]=array('ItemsLocation.location_id'=>$locationId);
    $order = array('Item.created' => 'desc'); // set order
    ...
    $items = $this->paginate('Item', compact('conditions','contain','order'));
    
    0 讨论(0)
  • 2020-12-11 10:18

    after 3 days searching, I found the way

    var $paginate = array('Post'=>array('group'=>'Post.id'));
    

    It's recomended to add group, because sometimes we will get duplicte posts in different categories

    $this->Post->bindModel(array('hasOne'=>array('CategoriesPost')), false);
    $out = $this->paginate('Post', array('CategoriesPost.category_id'=>array(1,4,7,6)));
    

    Add false to use bind model to all queries, not only to the following

    0 讨论(0)
提交回复
热议问题