使用 HABTM 模型的 CakePHP 分页

时间:2023-01-19
本文介绍了使用 HABTM 模型的 CakePHP 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在使用 HABTM 关系创建分页时遇到了一些问题.一、表和关系:

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

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

因此,请求具有请求来自来自的位置和请求将的位置.对于这个问题,我只关心to"位置.

So, a Request has a Location the request is coming from and a Location the Request is going to. For this question, I'm only concerned about the "to" location.

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

(* as "ToLocation")

在我的 RequestController 中,我想对请求的 ToLocation 中的所有项目进行分页.

In my RequestController, I want to paginate all the Items in a Request's 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:

And this is failing, because it is generating this SQL:

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

我不知道如何让它实际使用 $paginate...

I can't figure out how to make it actually use the "contain" argument of $paginate...

有什么想法吗?

推荐答案

我已经能够让它在一定程度上工作,但解决方案并没有让人觉得很老套.

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
        . ")"
    )
);

这篇关于使用 HABTM 模型的 CakePHP 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:长轮询锁定其他 AJAX 调用 下一篇:PHP 日期字符串格式

相关文章

最新文章