添加条件以在分页查询中连接表(CakePHP 2.0.4)

时间:2015-03-16 14:01:37

标签: php cakephp pagination

我是cakephp的新手。我必须在基于cakephp的应用程序中做一些改进。在那里,有类别和图像模型。在图像表中有很多图像。默认类别图像和其他类别相关图像详细信息将保留在该表中。它将在列表类别的第2页(分页)中显示以下查询。

SELECT `Category`.`id`, `Category`.`name`, `Category`.`slug`, `Category`.`meta_description`, `Category`.`meta_keywords`, `Category`.`sort`, `Category`.`color`, `Category`.`bgcolor`, `Category`.`modified`, `Category`.`created` FROM `categories` AS `Category`   WHERE 1 = 1   ORDER BY `sort` ASC  LIMIT 20, 20

SELECT `Image`.`id`, `Image`.`path`, `Image`.`size`, `Image`.`tags`, `Image`.`default`, `Image`.`category_id`, `Image`.`modified`, `Image`.`created` FROM `images` AS `Image` WHERE `Image`.`category_id` IN (60, 17, 9, 33, 71, 18, 73, 30, 58, 54, 3, 44, 64, 66, 67, 11, 53, 16, 23, 68)

但实际上,第二个查询需要像:

SELECT `Image`.`id`, `Image`.`path`, `Image`.`size`, `Image`.`tags`, `Image`.`default`, `Image`.`category_id`, `Image`.`modified`, `Image`.`created` FROM `images` AS `Image` WHERE `Image`.`default` = 1 AND `Image`.`category_id` IN (60, 17, 9, 33, 71, 18, 73, 30, 58, 54, 3, 44, 64, 66, 67, 11, 53, 16, 23, 68)

应该有

  

Imagedefault = 1   在WHERE子句中。

我的CategoriesController.php索引操作是:

public function index() {
    $this->Category->recursive = 1;
    $this->Category->Behaviors->attach('Containable');
    $this->paginate = array("contain"=>array("Image"));
    $search="";
    if(isset($this->params['named']['search'])){
        $search = str_replace("%20"," ", $this->params['named']['search']);
        $conditions = array(
            'OR' => array(
                array('Category.name LIKE' => '%'.$search.'%')
            )
        );

        $this->set('categories', $this->paginate($conditions));
    } else {
            $this->set('categories', $this->paginate());
    }
    $success = $this-> Session->read('success');
    $this->set(compact('search', 'success'));   
}

我的分类模型有:

public $hasMany = array(
    'Panel' => array(...),
    'Image' => array(
        'className' => 'Image',
        'foreignKey' => 'category_id',
        'dependent' => false,
        'conditions' => array('Image.default' => '1'),
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''    
    )   
);

所以,我需要过滤连接表images.default设置为'1'

2 个答案:

答案 0 :(得分:1)

在您的类别控制器中更改此行:

$this->paginate = array("contain"=>array("Image"));

为:

$this->paginate = array("contain"=>array("Image.default = 1"));

此处有更多信息:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-deeper-associations

答案 1 :(得分:0)

注意:默认递归级别为1

将两个条件合并为1

$this->paginate = array("contain"=>array("Image.default = 1"),"recursive" => 1);

或制作多个条件

$this->paginate = array('contain'=>array('Image'=>array('conditions'=>array('Image.default'=>1))))