Create CakePHP Page Using HABTM Models

I'm having trouble creating pagination using the HABTM relationship. First, tables and relationships:

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

Thus, the request has a location where the request comes from and a location to which the request is sent. On this issue, only the "location" bothers me.

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

(* as "ToLocation")

In my RequestController, I want to split pages into all the elements in a ToLocation request.

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

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

And this does not work, because it generates this SQL:

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

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

Any ideas?

+3
source share
3 answers

, .

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

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, ,

+11

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'));
+3

Source: https://habr.com/ru/post/1718336/


All Articles