簡體   English   中英

CakePHP與HABTM模型分頁

[英]CakePHP pagination with HABTM models

我在創建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$paginate ”參數...

有任何想法嗎?

經過3天的搜索,我找到了方法

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

建議添加組,因為有時我們會在不同的類別中獲得重復的帖子

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

添加false以將綁定模型用於所有查詢,而不僅僅是以下內容

要對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'));

我已經能夠讓它在某種程度上工作,但解決方案根本不會讓人感覺很好吃。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM