使用大结果集优化查询

时间:2013-09-21 18:41:45

标签: php cakephp model

我有一个CakePHP模型,我们称之为Thing,它有一个名为ItemView的关联模型。 ItemView表示Thing项的一个页面视图。我想显示已查看Thing次的次数,因此我在视图中执行以下操作:

<?php echo count($thing['ItemView']); ?>

这是有效的,但是随着时间的推移,这个查询的结果集会变得很大,因为它当前正在返回:

array(
    'Thing' => array(
        'id' => '1',
        'thing' => 'something'
    ),
    'ItemView' => array(
        (int) 0 => array(
            'id' => '1',
            'thing_id' => 1,
            'created' => '2013-09-21 19:25:39',
            'ip_address' => '127.0.0.1'
        ),
        (int) 1 => array(
            'id' => '1',
            'thing_id' => 1,
            'created' => '2013-09-21 19:25:41',
            'ip_address' => '127.0.0.1'
        ),
        // etc...
    )
)

如何调整模型find()以检索类似的内容:

array(
    'Thing' => array(
        'id' => '1',
        'thing' => 'something',
        'views' => 2
    )
)

没有将整个ItemView关系加载到内存中?

谢谢!

1 个答案:

答案 0 :(得分:0)

所以这很简单,我们可以使用countercache - 只要在ItemView添加/删除记录,Cake就会为您计数:

  • Thing.php型号

  • 无需更改
  • INT表格中添加新的viewsthings

  • ItemView.php模型中,添加counterCache,如下所示:

    public $belongsTo = array(
        'Thing' => array(
            'counterCache' => 'views'
        )
    );
    

然后下次当您通过ItemView添加/删除时,Cake会自动重新计算计数并缓存到views,所以下次执行查询时,您还需要确保将recursive = -1指定为@Paco Car has suggested in his answer

$this->Thing->recursive = -1;
$this->Thing->find(...); //this will returns array of Thing + the field "views"

// --- OR ---

$this->Thing->find(array(
    'conditions' => array(
        //... your usual conditions here
    ),

    //... fields, order... etc

    //this will make sure the recursive applies to this call, once only.
    'recursive' => -1
);