【问题标题】:CakePHP Pagination 'conditions' limited by $this->Session->read()CakePHP 分页“条件”受 $this->Session->read() 限制
【发布时间】:2014-01-04 04:06:22
【问题描述】:

我试图通过 $this->Session->read('Player.team_id')... 限制我的分页结果...以便登录用户只能看到他的相关团队成员。

PlayersController.php

public $paginate = array(
    'conditions' => array(
                'Player.team_id' => $this->Session->read('Player.0.Team.id')
             ),
    'limit' => 20,
    'order' => array('Player.fullname' => 'asc')
);

public function index() {
        $this->Paginator->settings = $this->paginate;
        $this->Player->recursive = 0;
        $this->set('players', $this->Paginator->paginate());
    }

这会导致查看播放器/索引时出错

错误:语法错误,意外的 T_VARIABLE
文件:/home/www/public_html/dev/app/Controller/PlayersController.php
线路:21

如果我硬编码下面的“条件”,那么它可以正常工作并且只检索我想要的记录

'conditions' => array('Player.team_id' => 1)

在 Player.php 模型登录操作中,它写入会话变量 Team.id 和 Team.name。

我在我的应用程序(视图和其他模型)中使用了 $this->Session->read else,它工作正常。它似乎在分页组件中不起作用?

【问题讨论】:

  • 你在使用会话组件吗?第 21 行还有什么代码?
  • 是的,会话组件正在 AppController.php 文件中加载。
  • 第 21 行:'Player.team_id' => $this->Session->read('Player.0.Team.id') $this->Session->read 有问题('Player.0.Team.id') 因为如果我将它替换为“1”,那么代码就可以工作。
  • 尝试$pid= $this->Session->read('Player.0.Team.id'); 并通过回显其值来检查,也可以'Player.team_id' =>$pid
  • @Nouphal.M 谢谢,我试过了,但错误现在出现在我放置此代码的行上。我什至尝试过 AuthComponent::user('Player.team_id') 但它会导致同样的问题。

标签: cakephp cakephp-2.4


【解决方案1】:

这只是无效的 PHP 语法,类成员只能用常量值初始化,即可以在编译时评估的值(字符串、数字、布尔值、数组等...)

改为在运行时在Controller::beforeFilter() 回调中分配会话值(或者在适当的情况下甚至直接在index() 操作中):

public $paginate = array(
    'limit' => 20,
    'order' => array('Player.fullname' => 'asc')
);

public function beforeFilter() {
    parent::beforeFilter();

    $this->paginate['conditions'] = array(
        'Player.team_id' => $this->Session->read('Player.0.Team.id')
    );
}

同样如 cmets 中所指出的,请确保您正在访问的会话密钥确实存在并保持预期值!

另请参阅http://www.php.net/manual/en/language.oop5.properties.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多