检查视图模板中对象是否存在或为空

Check if object exists or is empty in view template

如果结果对象包含任何条目,您如何检查在视图模板中

(已经有一个 similar question,但这个略有不同)

CakePHP 3 blog tutorial为例。他们展示了如何在一页上列出所有文章:

// src/Controller/ArticlesController.php
public function index() {
  $this->set('articles', $this->Articles->find('all'));
}

和视图模板:

<!-- File: src/Template/Articles/index.ctp -->
<table>
  <tr>
    <th>Id</th>
    <th>Title</th>
  </tr>
<?php foreach ($articles as $article): ?>
  <tr>
    <td><?= $article->id ?></td>
    <td>
      <?= $this->Html->link($article->title, ['action' => 'view', $article->id]) ?>
    </td>
</tr>
<?php endforeach; ?>
</table>

缺点:如果数据库中没有条目,HTML table 仍然呈现。

我怎样才能防止这种情况并显示像 "Sorry no results" insteat 这样的简单消息?

CakePHP 2我用了

if ( !empty($articles['0']['id']) ) {
  // result table and foreach here
} else {
  echo '<p>Sorry no results...</p>';
}

但是由于 $articles 现在是一个对象,所以它不再起作用了...是否有新的 "short way" 来检查结果对象?或者你通常先使用另一个foreach,比如

$there_are_results = false;
foreach ($articles as $article) {
  if ( !empty($article->id) ) {
    $there_are_results = true;
    break;
  }
}
if ( $there_are_results == true ) {
  // result table and second foreach here
} else {
  echo '<p>Sorry no results...</p>';
}

感谢您的提示。

您可以使用iterator_count()函数来了解集合中是否有结果:

if (iterator_count($articles)) {
 ....
}

您也可以使用集合方法获取第一个元素:

if (collection($articles)->first()) {
}

编辑:

从 CakePHP 3.0.5 开始,检查查询或结果集是否为空的最佳方法是:

if (!$articles->isEmpty()) {
    ...
}

我相信您可以从模板中调用 $articles->count() 。 (检查 0)

我一直在努力的事情..

if(!$articles->isEmpty()) {
gives error on empty value
Call to a member function isEmpty() on null
<?php if(iterator_count($articles)) { ?>
Argument 1 passed to iterator_count() must implement interface Traversable, null given
<?php if (collection($articles)->first()) {?>
Only an array or \Traversable is allowed for Collection

我得到了 工作,如果你在控制器中呈现不同的视图,就会出现问题 $this->render('index'); 对于函数,您应该在设置值后执行此操作