如何根据关联模型的值过滤分页结果? (CakePHP 2.x)

时间:2015-11-25 18:09:05

标签: php mysql cakephp cakephp-2.0 cakephp-2.x

我在cakephp中有3个模型

  1. 属性
  2. property id   name    area    sub area
    1             name    1       india   --
    2             name    2       india   --
    3             name    3       uk    --
    4             name    4       pakistan  --
    
    1. 门户
    2. portals_id  portal name
      1           google xml
      2           zameen.com
      3           buy property
      4           rent property
      
      1. property_portals
      2. property_portals_id    portal_id    property_id
        1                      1            1            
        2                      1            1
        3                      2            2 
        4                      2            2 
        5                      2            3
        6                      1            4 
        7                      1            1
        

        我有一个网格系统,用于搜索不同属性的属性 现在我想只搜索那些将在特定门户网站上做广告的属性。

        我正在使用分页。

        $this->set('properties', $this->Paginator->paginate('Property'));
        

2 个答案:

答案 0 :(得分:0)

我建议你试试CakeDC Search plugin。您可以配置几乎任何类型的搜索(无论多么复杂),并且它与分页兼容。

first example in the docs包含有关如何配置$filterArgs以执行HABTM搜索的示例。

答案 1 :(得分:0)

我假设您已在模型中声明了HABTM关系,如下所示:

class Property extends AppModel {

public $hasAndBelongsToMany = array(
    'Portal' => array(
        'className' => 'Portal',
        'joinTable' => 'property_portals',
        'foreignKey' => 'portal_id',
        'associationForeignKey' => 'property_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    )
);

反之亦然,您的门户网站模型

然后你应该可以为你的分页设置查询参数:

$this->Property->Portal->paginate('Post', array(
    'conditions' => array(
        'Portal.id' => $idOfPortalYouWantToSearch
    ), 'order' => array(
        'COUNT(property_portals_id )'
    )
));

然后查询:

$this->set('properties', $this->Paginator->paginate('Property'));

没有测试它,但它应该工作。