有没有办法检查蛋糕php中是否存在记录.我知道有一个功能.CakePHP 2
$this->Notes->id = $id;
if (!$this->Notes->exists())
{
throw new NotFoundException(__('Invalid Notes'));
}
Run Code Online (Sandbox Code Playgroud)
但默认情况下,它会检查列id如何检查自定义列,假设它是note_id.我的attemts是从这里引用的
尝试#1
if (!$this->Noteshistory->exists(['note_id'=>$id]))
{
throw new NotFoundException(__("Invalid Note "));
}
Run Code Online (Sandbox Code Playgroud)
还尝试设置note_id
$this->Noteshistory->note_id = $id;
if (!$this->Noteshistory->exists(['note_id'=>$id]))
{
throw new NotFoundException(__("Invalid Note "));
}
Run Code Online (Sandbox Code Playgroud)
但没有运气.
如果结果对象包含任何条目,如何在视图模板中检查?
以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 …Run Code Online (Sandbox Code Playgroud)