CakePHP 使用小技巧

知道主鍵 ID 更新一條數據,代碼示例:

php$this->Order->id = $id;
$this->Order->saveField('status', $status);

點讚的時候須要+1,如何更新數據庫?

php$this->Widget->updateAll(
    array('Widget.numberfield' => 'Widget.numberfield + 1'),
    array('Widget.id' => 1)
);

如何經過主鍵最簡單的方式獲取到一條數據?

php// 只獲取name字段信息
$this->User->read('name', $id);
// 獲取全部信息
$this->User->read(null, $id);

CakePHP控制器如何返回上一頁?

php$this->redirect($this->referer());

CakePHP A控制器調用B控制器?

php$this->requestAction(
    array('controller'=>'Wx','action'=>'aa'),
    array('data'=>
        array('xing'=>'A1','ming'=>'A2')
    )
);

這樣能夠在A控制器調用B控制器方法,並且在後面傳參過去,用$this->request->data獲取參數值。php

輸出單個頁面執行的 SQL 語句

php$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

Model要改一下名字才能用。sql

模糊和 OR 搜索示例:

php$this->User->find('all', array(
   'conditions' => array(
        'OR' =>array(
            array('nickname like ' => "%$keyword%"),
            array('User.id' => $keyword),
        )
    ),
    'fields' => 'User.id,User.nickname'
));

find 的 語法糖

php#findAllBy<fieldName>(string $value, array $fields, array $order, int $limit, int $page, int $recursive)
$this->Product->findAllByOrderStatus('3');
$this->User->findAllByUsernameAndPassword('jhon', '123');
$this->User->findAllByEmailOrUsername('jhon', 'jhon');
$this->User->findAllByLastName('psychic', array(),array('User.user_name' => 'asc'));

#findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]);
$this->Recipe->findByType('Cookie');
$this->User->findByEmailOrUsername('jhon','jhon');
$this->User->findByUsernameAndPassword('jhon','123');

CakePHP saveAll 的用法:

phpfor ($i=0; $i < count($data['product_id']); $i++) {
    $item[$i]['DiscountProduct']['discount_id'] = $this->Discount->id;
    $item[$i]['DiscountProduct']['discount'] = $data['discount'][$i];
}
$this->DiscountProduct->saveAll($item);

若是要是有 CakePHP 自帶和 HTML 結合的 FORM

必須在 Controller 的 action 裏面使用這個:$this->request->data = $data; 修改的時候才能讀取數據,而且view裏面的 form 要使用 CakePHP 的數據庫

php<?php echo $this->Form->create('PrintAd', array('type'=>'post')); ?>

CakePHP 中表有如下字段名,則自動更新時間

sql`created` datetime NOT NULL,
`modified` datetime NOT NULL,

CakePHP 自帶圖片+連接

phpecho $this->Html->link(
     $this->Html->image($value['PrintClient']['weixin_code_img'], array('width'=>'60px')),
     $value['PrintClient']['weixin_code_img'],
     array('escape' => false)
);

CakePHP 查詢的時候表聯接

php$options['joins'] = array(
    array(
        'table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )    
    ));
$Item->find('all', $options);

CakePHP 獲取當前域名

phpRouter::fullbaseUrl()

CakePHP 控制器構造函數的用法:

phppublic function__construct($request = null, $response = null)
{
    parent::__construct($request, $response);
    # code...
}

CakePHP 視圖獲取 URL 的參數值

php#array(): 
$this->params->pass
#第一個值:
$this->params->pass[0]

CakePHP 聯表分頁

php$this->loadModel('WifiList');
$this->SearchPagination->setup('WifiList');
$this->request->data['WifiList']['seller_id'] = SELLER_ID;
$this->paginate = array(
    'fields' => array('WifiList.*', 'WxPersistentQrcodes.ticket'),
    'conditions' => $this->WifiList->parseCriteria($this->request->data['WifiList']),
    'order' => 'WifiList.id desc',
    'joins' => array(
        array(
            'table'=>'wx_persistent_qrcodes',
            'alias'=>'WxPersistentQrcodes',
            'type'=>'LEFT',
            'conditions'=>array(
                'WifiList.wx_p_qrcode_id=WxPersistentQrcodes.scene_id and WxPersistentQrcodes.seller_id='.SELLER_ID
            )
        )    
    ),
    'limit' => 10
);
$data = $this->paginate('WifiList');
$this->set(compact('data'));

CakePHP 拋出異常

phpif(!$id){
    throw new NotFoundException();
}

CakePHP 跳轉連接

php$this->redirect(array(
    'controller'=>'dist',
    'action'=>'result',
    $status,
    '?'=>array('sid'=>SELLER_ID,)
));

CakePHP Model 使用其餘模型

php// the other model to load & use
App::uses('AnotherModel', 'Model');
class MyModel extends AppModel {
    public $name = 'MyModel';

    public function test() {
        // load the Model
        $anotherModel = new AnotherModel();
        // use the Model
        $anotherModel->save($data);
    }
}
相關文章
相關標籤/搜索