【问题标题】:using cakephp, how do I handle model operations that return no results so my view doesn't break?使用 cakephp,我如何处理不返回结果的模型操作,这样我的视图就不会中断?
【发布时间】:2010-03-04 15:55:27
【问题描述】:

在我的控制器中,我有可以返回空结果的模型操作。我已经设置视图以使用 foreach 循环显示结果。但是,如果模型操作为空并且不返回任何结果,那么我认为 foreach 循环正在中断。

这是操作:

$match3 = $this->Draw->Match-> find('all',array('conditions'=>array('Match.draw_id'=>$id, 'Match.round_id'=> 1, 'Match.match_position' => 3)));

我需要在模型操作中添加什么才能返回 null?还是 null 是处理这个问题的最佳方式?

如果没有数据,那么我不希望显示任何内容。

我确实尝试过,但出现未定义的索引错误:

如果 (!$match3) 返回空值; 别的 返回 $match3;

在处理空模型操作方面是否有最佳实践?

非常感谢。 -保罗

【问题讨论】:

    标签: cakephp model null find


    【解决方案1】:

    IMO,“最佳实践”不是 CakePHP 特有的。如果您的结果将其设置为空,那么将这一事实告知您的用户至关重要。这是一个简单的测试(在这种情况下是一个空数组,如 Travis 所示)和一个简单的结果。在我看来,我通常会这样做:

    <?php if( empty( $match3 ) ): ?>
      <h2>Display an appropriate empty set message.</h2>
    <?php else: ?>
      # do whatever you need to do to display the result set
    <?php endif; ?>
    

    【讨论】:

      【解决方案2】:

      如果你的查找操作没有结果,它只会返回一个空数组。

      在您看来,只需在输出该部分之前添加一些逻辑以确保 $match3 不是空数组。例如,在视图中

      <?php
       // some code here to output part of the page
       if( !empty( $match3 ) )
        foreach( $match3 as $matches )
         ; // do something with $matches
       // rest of your view code
      ?>
      

      【讨论】:

        【解决方案3】:

        很大程度上取决于您的应用,以下响应可能是合适的:

        $result = $this->Model->find(…);
        
        if (!$result) {
            // redirect to another page and display message
            $this->Session->setFlash('No results found');
            $this->redirect(array('action' => 'index'));
        }
        

        if (!$result) {
            // throw a 404 (or any other) error
            $this->cakeError('error404');
        }
        

        同样,这在很大程度上取决于应用程序和相关操作,尤其是 404 不应该作为标准响应。在许多情况下,最好按照Rob 的建议在视图中处理它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-28
          • 1970-01-01
          • 2014-01-25
          • 1970-01-01
          • 2014-03-21
          • 1970-01-01
          • 2018-12-20
          • 2021-06-30
          相关资源
          最近更新 更多