删除单条记录
使用CakePHP在数据库表中删除条记录非常简单CakePHP模型默认继承有个专门服务此目思路方法(method)我们接下来会看到我们如何使用这模型思路方法来删除我们books表中记录
动手时间:删除单个记录
1在BooksController中(/app/controllers/books_controller.php)添加个新操作delete():
<?php
BooksController extends AppController {
var $name = 'Books';
var $helpers = .gif' />('Form' );
function index {
$books = $this->Book->find('all',
.gif' />(
'fields' => .gif' />(
'Book.id',
'Book.isbn',
'Book.title',
'Book.author_name'
),
'order' => 'Book.title ASC'
)
);
$this->('books', $books);
}
function add {
(!empty($this->data)) {
$this->Book->create;
(!!$this->Book->save($this->data)) {
$this->Session->Flash('Book is Saved!', true);
$this->redirect(.gif' />('action'=>'index'));
}
}
}
function edit($id=null) {
(!$id && empty($this->data)) {
$this->Session->Flash('Invalid Book', true);
$this->redirect(.gif' />('action'=>'index'));
}
(!empty($this->data)) {
$this->Book->create;
(!!$this->Book->save($this->data)) {
$this->Session->Flash('Book Updated!', true);
$this->redirect(.gif' />('action'=>'index'), null, true);
}
}
(empty($this->data)) {
$this->data = $this->Book->read(null, $id);
}
}
function delete($id = null) {
(!$id) {
$this->Session->Flash('Invalid Book', true);
}
($this->Book->del($id)) {
$this->Session->Flash('Book is deleted', true);
}
{
$this->Session->Flash('Could not delete Book', true);
}
$this->redirect(.gif' />('action'=>'index'));
}
}
?>
2现在在 /books/index操作对应视图文件中紧挨着“编辑”链接添加个“删除”链接
<table>
<thead>
<th>ISBN</th><th>Title</th><th>Author</th><th>Actions</th>
</thead>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['Book']['isbn'] ?></td>
<td><?php echo $book['Book']['title'] ?></td>
<td><?php echo $book['Book']['author_name'] ?></td>
<td>
<?php echo $html->link('edit', .gif' />('action'=>'edit',
$book['Book']['id']) ) ?>
<?php echo $html->link('delete', .gif' />('action'=>'delete',
$book['Book']['id']) ) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
3在浏览器中打开下面这个链接: http://localhost/data-access/books/点击书后面删除链接它应该会删除对应记录然后它再将我们带回到index操作上来条信息也会显示在列表顶部告诉我们记录已经成功删除
如何回事?
首先我们在BooksController中添加了个名为delete新操作delete(删除)操作会接受个参数 $id我们首先检查了 $id 是否为空如果它确为空我们会设置条信息显示图书id无效
(!$id) {
$this->Session->Flash('Invalid Book', true);
}
在条件语句的后我们试图通过模型del思路方法来删除记录
$id会被作为参数传送给del 思路方法以指定删除哪条记录如果删除成功条件语句会返回个真值我们也会设置条信息成称图书记录已经成功删除
($this->Book->del($id)) {
$this->Session->Flash('Book is deleted', true);
}
如果删除失败在括号内就会执行起来它会设置条信息称无法删除某条图书信息
最后我们将用户转跳到 /books/index 操作上来注意 /books/delete 操作并不包含任何视图实际上在任何情况下都无需视图它会把用户转跳到 /books/index 操作上来
我们使用了html助手link思路方法在/books/index操作对应视图文件添加了个新链接紧挨着edit链接
<td><?php echo $html->link('delete', .gif' />('action'=>'delete', $book['Book']['id']) ) ?></td>
这个链接和我们的前创建“编辑”链接非常类似
现在如果我们点击任意本图书后面删除链接它就会/books/delete操作来执行删除然后它会将我们带回到/books/index操作上来并在页面顶部显示条信息称图书信息记录已经删除
图片看不清楚?请点击这里查看原图(大图)
最新评论