【问题标题】:How to paginate joined many-to-many table with where clause in cakephp?如何使用 cakephp 中的 where 子句对连接的多对多表进行分页?
【发布时间】:2015-11-10 09:59:34
【问题描述】:

我有两张表被另一张连接起来。表是:

PostsTable

$this->belongsToMany('Categories', [
    'through' => 'CategoryPost'
]);

类别表

$this->belongsToMany('Categories', [
    'through' => 'CategoryPost'
]);

CategoryPostTable

$this->belongsTo('Categories', [
    'foreignKey' => 'category_id'
]);

$this->belongsTo('Posts', [
    'foreignKey' => 'post_id'
]);

我想显示特定类别的帖子。例如“设计”类别中的帖子。

路由定义为:

$routes->connect('/blog/archive/:safe_name', ['controller' => 'Posts', 'action' => 'category'], ['pass' => ['safe_name']]);

Posts 控制器中的category 动作定义如下:

class PostsController extends AppController
{
    ...
    public function category($safe_name = null)
    {
        $this->paginate = [
            'contain' => ['Photos', 'Categories']
        ];

        $posts = $this->Posts->find()->matching('Categories', function ($q) {
            return $q->where(['Categories.safe_name' => $safe_name]);
        });
        $this->set('posts', $this->paginate($posts));
        $this->set('_serialize', ['posts']);
    }
    ...
}

但我得到的是:

Undefined variable: safe_name [APP/Controller\PostsController.php, line 188

谁能帮我解决这个问题!我该怎么做? 抱歉英语不好。

顺便说一句,我的 cakephp 版本是 3.0。

【问题讨论】:

    标签: php cakephp pagination cakephp-3.0


    【解决方案1】:

    php 中的闭包不会继承更高范围的变量

    导致错误信息的代码是这样的:

    $posts = $this->Posts->find()->matching('Categories', function ($q) {
        return $q->where(['Categories.safe_name' => $safe_name]);
    });
    

    因为在闭包中,变量$save_name 没有定义。要修复该错误,请使用use

    $posts = $this->Posts->find()->matching('Categories', function ($q) use ($safe_name) {
        return $q->where(['Categories.safe_name' => $safe_name]);
    });
    

    【讨论】:

    • tnx 很多,修复了错误,但弹出另一个错误:Undefined index: pageCount [CORE\src\View\Helper\PaginatorHelper.php, line 634
    • 你没有调用分页,所以这并不奇怪。
    • 哦,我错了,我会更新帖子,感谢您的大力帮助!
    • 如何检查类别及其在视图中的值?我这样做但出错了:if($post->has('category')) { foreach ($post->category as $category) { echo $category->name; }}
    • 这是第三个问题 ;) - 请注意 asking chameleon questions - 如果您有新的疑问,与您最初提出的问题直接相关:问一个新问题。
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-04-27
    • 2011-03-24
    相关资源
    最近更新 更多