一步一步学习CakePHP(三)model

model,它使领域逻辑从表现层和独立的业务逻辑中剥离出来,从理论上来说,model实现了ActiveRecord,所以它不仅仅是是一个数据的抽象层,此外,还提供了许多有用的方法,可以方便简洁的操作数据库,在CakePHP中,一个model经常代表了数据库中的某张表。

一:创建数据库和model

我们首先创建数据库和表:

CREATE DATABASE `data-access`;

USE `data-access`; 
CREATE TABLE `books` ( 
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`isbn` varchar( 10 ) NOT NULL , 
`title` varchar( 127 ) NOT NULL , 
`description` text NOT NULL , 
`author_name` varchar( 127 ) NOT NULL 
)

modelbook.php

<?php 
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
class Book extends AppModel{ 
    var $name = 'Book'; 

?>

controller:books_controller.php

<?php 
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
class BooksController extends AppController{ 
    var $name = 'Books'; 
    var $scaffold; 

?>

注意此处的var $scaffold,脚手架会创建一个基本的应用程序,会自动创建CRUD功能。

clip_image002

二:检索数据

CakePHP中,已经存在了很多方法,可以使开发者很方便地从数据库检索到数据。

修改books_controller.php,去掉脚手架:

<?php 
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
class BooksController extends AppController{ 
    var $name = 'Books'; 
    //var $scaffold; 
    function index(){ 
        $books = $this->Book->find('all', 
                array( 
                    'fields' =>array( 
                        'Book.isbn', 
                        'Book.title', 
                        'Book.author_name' 
                    ), 
                    'order' => 'Book.title ASC' 
                ) 
                ); 
        $this->set('books',$books); 
    } 

?>

创建/app/views/books/index.ctp

<table> 
  <thead> 
    <th>ISBN</th><th>Title</th><th>Author</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> 
  </tr> 
  <?php endforeach; ?> 
</table>

CakePHP中,一个model的实例,会被当作controller的属性,如$this->Book,而find()就是book model的一个方法,第一个参数all,就是说明需要获得全部的数据。

clip_image004

find()方法是非常灵活的,如一个类似这样的SQL查询

SELECT `Book`.`isbn`, `Book`.`title`, `Book`.`author_name` 
FROM `books` AS `Book` 
WHERE `Book`.`title` LIKE 'A%' 
ORDER BY `Book`.`isbn` DESC 
LIMIT 2;

我们可以用find()来实现:

'conditions' => array('Book.title LIKE' => 'A%'),

下面详细叙述一下find的参数,第一个可以是all、first、count,第二个参数为一数组,数组的key可以是:conditions、fields、order、limit、offset。

三:保存数据

books_controller.php增加add():

function add(){ 
    if(!empty($this->data)){ 
        $this->Book->create(); 
        if(!!$this->Book->save($this->data)){ 
            $this->Session->setFlash('Book is Saved!',true); 
            $this->redirect(array('action'=>'index')); 
        } 
    } 
}

app/views/books/add.ctp:

<?php echo $form->create('Book');?> 
      <fieldset> 
          <legend>Add New Book</legend> 
      <?php 
         echo $form->input('isbn'); 
         echo $form->input('title'); 
         echo $form->input('description'); 
         echo $form->input('author_name'); 
      ?> 
      </fieldset> 
   <?php echo $form->end('Submit');?>

clip_image006

在add中,我们首先判断是否从view中返回数据,如果没有返回,那么将会呈现view,当我们提交form表单的时候,数据将会提交到add action。

我们用Book model作为参数,传给FormHelper的create方法,然后,使用其input方法添加input元素,并且使用数据库表中的字段名称作为参数,这将会帮助FormHelper自动绑定。最后,按下提交按钮,所有的数据将会被提交给add,提交的数据可以通过controller的属性$this->data获得。

四:更新记录

books_controller.php增加edit():

function edit($id=null){ 
    if(!$id && empty ($this->data)){ 
        $this->Session->setFlash('Invalid Book',true); 
        $this->redirect(array('action'=>'index')); 
    } 
    if(empty ($this->data)){ 
        $this->data = $this->Book->read(null,$id); 
    } 
    else{ 
        $this->Book->create(); 
        if(!!$this->Book->save($this->data)){ 
            $this->Session->setFlash('已经更新',true); 
            $this->redirect(array('action'=>'index'),null,true); 
        } 
    } 
}

app/views/books/edit.ctp:

<?php echo $form->create('Book');?> 
   <fieldset> 
       <legend>Edit Book</legend> 
      <?php 
         echo $form->input('id'); 
echo $form->input('isbn'); 
         echo $form->input('title'); 
         echo $form->input('description'); 
         echo $form->input('author_name'); 
      ?> 
   </fieldset> 
<?php echo $form->end('Submit');?>

修改app/views/books/index.ctp:

<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/'.$book['Book']['id']) 
       ?></td> 
  </tr> 
  <?php endforeach; ?> 
</table>

clip_image008

clip_image010

由此可见,save()在add和edit中都可以使用,不同的是,在edit中,id主键必须在$data中存在。

五:删除记录

books_controller.php增加delete():

function delete($id = null){ 
    if(!$id){ 
        $this->Session->setFlash('Invalid Book',true); 
    } 
    else if($this->Book->del($id)){ 
        $this->Session->setFlash('已经删除',true); 
    } 
    else{ 
        $this->Session->setFlash('删除失败',true); 
    } 
    $this->redirect(array('action'=>'index')); 
}

修改app/views/books/index.ctp:

<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/'.$book['Book']['id']) 
       ?> 
        <?php echo $html->link('删除', array('action'=>'delete', 
                              $book['Book']['id']) ) ?> 
    </td> 
  </tr> 
  <?php endforeach; ?> 
</table>

clip_image012

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值