CakePHP的分页与HABTM模型(CakePHP pagination with HABTM m

2019-07-19 02:29发布

我有一些问题与HABTM关系创建分页。 首先,表和关系:

requests (id, to_location_id, from_location_id)
locations (id, name)
items_locations (id, item_id, location_id)
items (id, name)

因此,请求具有地理位置的请求和位置的要求是来了。 对于这个问题,我只关心“到”位置。

Request --belongsTo--> Location* --hasAndBelongsToMany--> Item

(* as "ToLocation")

在我RequestController,我要在分页请求的ToLocation的所有项目。

// RequestsController
var $paginate = array(
    'Item' => array(
        'limit' => 5,
        'contain' => array(
            "Location"
        )
    )
);

// RequestController::add()
$locationId = 21;
$items = $this->paginate('Item', array(
    "Location.id" => $locationId
));

这就是失败的,因为它是产生这个SQL:

SELECT COUNT(*) AS count FROM items Item   WHERE Location.id = 21

我无法弄清楚如何使它真正使用“遏制”的说法$paginate ...

有任何想法吗?

Answer 1:

3天后搜索,我找到了路

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

它recomended添加组,因为有时候我们会得到不同的类别duplicte岗位

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

添加使用绑定模式,所有的查询,不但以下



Answer 2:

为了分页HABTM,需要临时绑定“hasOne”加入模型到模型,你分页:

// 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'));


Answer 3:

我已经能够得到它有点工作,但解决方案不会觉得很cakey可言。

$items = $this->paginate(
    $this->Request->ToLocation->Item,
    array(
        "Item.id IN ("
        . "SELECT item_id FROM items_locations "
        . "WHERE location_id = " . $locationId
        . ")"
    )
);


文章来源: CakePHP pagination with HABTM models