0

我是 cakePHP 的初学者。收到以下错误

错误:调用非对象上的成员函数 find() 文件:/var/www/html/cakephp/app/Model/Post.php
行:11

有很多关于该错误的相关帖子,但我无法通过引用这些帖子来跟踪问题。

我的模型 Post.php

<?php

class Post extends AppModel {
public $validate = array(
'title' => array('rule' => 'notBlank'),
'body' => array('rule' => 'notBlank'));
public $belongsTo = 'Category';
public function actual(){ 
return $this->Post->find('all', array('conditions' => array('Post.deleted' => 0)));
}
}
?>

我在控制器中的 index()

public function index() 
{
    $actual = $this->Post->actual();
    $this->Post->recursive = 0;
    $this->paginate = array ('limit' => 5);
    $this->set('actuals', $this->paginate());
}

我正在尝试实现软删除逻辑。如果用户单击删除,则数据库中已删除列中的标志将更改为 1 以获取相应的数据。因此,通常我必须显示已删除 = 0 的数据。

我可以通过在我的索引视图中放置一个 if 条件来实现它,但这很不方便,我想在模型本身过滤数据(如果可能的话)任何帮助将不胜感激。谢谢

更新 在我的模型中我改变了

return $this->Post->find

return $this->find

现在错误消失了,但它显示了所有数据,甚至是已删除的数据!

4

2 回答 2

1

您的模型 Post 是正确的,但在控制器中不正确。

解决方案1 ​​[简单]:

  • 型号:不变。函数“实际值”可以用于其他目的,但在这种情况下不需要。

  • 控制器:

    public function index() 
    {
        $this->Post->recursive = 0;
        $this->paginate = array (
            'limit' => 5,
            'conditions' => array(
                array('Post.deleted' => 0)
            )
        );
        $this->set('actuals', $this->paginate());
    }
    

解决方案2:

  • 模型:

    <?php
    
    class Post extends AppModel {
        public $findMethods = array('actuals' => true);
    
        public $validate = array(
            'title' => array('rule' => 'notBlank'),
            'body' => array('rule' => 'notBlank'));
        public $belongsTo = 'Category';
        protected function _findActuals($state, $query, $results = array()){ 
            if ($state === 'before') {
                $query['conditions']['Post.deleted'] = false;
    
                return $query;
            }
    
            return $results;
        }
    }
    ?>
    
  • 控制器:

     public function index() 
     { 
          $this->Post->recursive = 0;
          $this->paginate = array ('limit' => 5, 'findType' => 'actuals');
          $this->set('actuals', $this->paginate());
     }
    

参考:Cakephp 2.x - 自定义查找类型

于 2015-12-15T06:44:38.330 回答
0

终于得到了输出

public function index() 
    {
        $this->Post->recursive = 0;
        $this->Paginator->settings = array('conditions' => array('Post.deleted' => 0),'limit' => 5);        
        $this->set('actuals', $this->Paginator->paginate());
    }

上述更改给了我一个正常的输出,但仍然无法在模型中过滤数据。如果您认为这也很不方便,请告诉我,我想学习高效的编码 :) 谢谢!

于 2015-12-15T06:46:30.040 回答