Oop*_*'oh 3 cakephp-3.0 cakephp-3.x
如果结果对象包含任何条目,如何在视图模板中检查?
以CakePHP 3博客教程为例.他们展示了如何在一个页面上列出所有文章:
// src/Controller/ArticlesController.php
public function index() {
$this->set('articles', $this->Articles->find('all'));
}
Run Code Online (Sandbox Code Playgroud)
和视图模板:
<!-- 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>
Run Code Online (Sandbox Code Playgroud)
缺点:如果数据库中没有条目,则仍会呈现HTML表.
如何防止这种情况并显示一条简单的消息,例如"抱歉没有结果"的内容?
在CakePHP 2
我用过
if ( !empty($articles['0']['id']) ) {
// result table and foreach here
} else {
echo '<p>Sorry no results...</p>';
}
Run Code Online (Sandbox Code Playgroud)
但由于$articles
现在它已成为一个对象,因此不再起作用......是否有新的"简短方法"来检查结果对象?或者你是否通常先使用另一个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>';
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的提示.
Jos*_*uez 21
您可以使用该iterator_count()
函数来了解集合中是否有结果:
if (iterator_count($articles)) {
....
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用集合方法获取第一个元素:
if (collection($articles)->first()) {
}
Run Code Online (Sandbox Code Playgroud)
编辑:
从CakePHP 3.0.5开始,检查查询或结果集空虚的最佳方法是:
if (!$articles->isEmpty()) {
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7816 次 |
最近记录: |