Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
paginator未传递CakePHP自定义字段_Php_Cakephp_Cakephp 3.0 - Fatal编程技术网

paginator未传递CakePHP自定义字段

paginator未传递CakePHP自定义字段,php,cakephp,cakephp-3.0,Php,Cakephp,Cakephp 3.0,我的相册模型 public function index_list() { $data = $this->find() ->contain(['Images' => function($q) { $q->select([ 'total' => $q->func()->count('image_id') ]) ->group(['

我的
相册模型

public function index_list()
{
    $data = $this->find()
    ->contain(['Images' => function($q) {
            $q->select([
                 'total' => $q->func()->count('image_id')
            ])
            ->group(['photoalbum_id']);
            return $q;
        }
    ]);

    foreach ($data as $row)
    {
        $row->image_count = 0;
        if (isset($row->images{0}->total))
        {
            $row->image_count = $row->images{0}->total;
        }
        unset($row->images);
    }       
    return $data;
}
基本上将
image\u count
添加到行中

在我的控制器中,我使用:

<?php
class PhotoalbumsController extends AppController
{
    public $paginate = [
        'limit' => 2,
        'order' => ['id' => 'desc']
    ];

    public function index()
    {
        $photoalbums = $this->paginate($this->Photoalbums->index_list());
        $this->set(compact('photoalbums'));
    }

分页器将选项应用于查询,例如限制,这将导致查询被标记为脏查询,从而清除任何可能缓冲的结果集,因此您在那里所做的是迭代要删除的结果集,并修改将不会下降到任何位置的对象(实体)

您根本不应该依赖缓冲结果集,如果您需要可靠地修改查询的结果,那么您应该使用结果格式化程序或map/reduce,这两种工具在每次执行查询时都应用于结果:

$query = $this
    ->find()
    ->contain([
        'Images' => function($q) {
            $q
                ->select([
                    'total' => $q->func()->count('image_id')
                ])
                ->group(['photoalbum_id']);

            return $q;
        }
    ])
    ->formatResults(function (\Cake\Collection\CollectionInterface $results) {
        return $results->map(function ($row) {
            $row['image_count'] = $row['images'][0]['total'];

            return $row;
        });
    });

return $query;
也就是说,您还可以通过加入关联(而不是包含关联)并在主查询中选择列,在SQL级别直接处理此问题:

$query = $this->find();
$query
    ->select(['image_count' => $query->func()->count('Images.id')])
    ->enableAutoFields()
    ->leftJoinWith('Images')
    ->group('Photoalbums.id');
当然还有计数器缓存行为

另见


感谢您的详尽回答!我一回到家就去测试。我确实看到了计数器缓存功能,但没有让它与链接和取消数据链接一起工作。