phalcon Model模型的基本使用與常用操作(增刪改查)
阿新 • • 發佈:2019-01-08
phalcon模型命名方式使用駝峰法,主要是用來跟資料庫互動,應用程式中的大部分業務邏輯都將集中在模型裡,l這裡把常用的模型操作做下筆記,phalcon框架的模型方式和框架提供的一些常用操作方法。
新建一個模型app/models/Rebots.php
class Rebots extends \Phalcon\Mvc\Model
{
// 官方建議在模型中預先定義好所有的列,這樣可以減少模型記憶體的開銷以及記憶體分配。
public $id;
public $name;
public $type;
public $year;
// initizelize 在請求期間僅會被自動呼叫一次,目的是為模型例項進行初始化
public function initialize()
{
// setSource()方法指定資料庫表
$this->setSource('rebots');
}
/**
*
* 獲取一條記錄
* 接受關聯陣列作為查詢條件:
* @param $condition int|array 比如 id=1;
* 引數說明: 比如 array("name='張三'")
*
* @return \Phalcon\Mvc\Model 返回一個模型例項
*/
public function getFirst($condition)
{
return $this->findFirst($condition);
}
/**
* 獲取多條記錄
* 接受關聯陣列作為查詢條件:
* @param $conditoin string|array
*說明:
* 1: 沒有條件獲取所有記錄
*
* 2: 字串 name='張三' 獲取name等於張三的記錄
*
* 3: ["id < 5", 'order' => 'id desc', 'limit' => 10]
*
* 4: 如果需要通過外部資料(比如使用者輸入)或變數來查詢記錄,
* 則必須要用`Binding Parameters`(繫結引數)的方式來防止SQL注入.
* ["id < ':id:'",
'limit' => 10,
'bind'=>5]
*
* 5:繫結引數型別
'bind' => ['id' => 5],
['bindTypes' => ['id' => \Phalcon\Db\Column::BIND_PARAM_INT]]]
* @return \Phalcon\Mvc\ResultsetInterface
*/
public function getMoreData($conditoin='')
{
return $this->find($conditoin);
}
/**
* 查詢後置方法
* 獲取記錄的初始化以及準備
* 從資料庫中獲取了一條記錄之後,自動呼叫,可以為某些欄位做處理
*
*/
public function afterFetch()
{
$this->name = explode(' ', $this->name);
}
// 在呼叫save方法之前呼叫
public function beforeSave()
{
$this->name = 'before Save';
}
// 在呼叫save方法之後呼叫
public function afterSave()
{
$this->name = 'after save';
}
/**
*更新資料/插入資料
*$data = array(); 需要更新的資料
*update更新資料
*save 更新/插入
*/
public function updateRecord($data=array())
{
// update方法更新一條語句,會根據id自動更新對應的紀錄
$data = array(
'id' => 9,
'name' => '張三',
'age' => '18',
'address' => 'beijing'
);
$this->update($data);
// save 方法可以更新和修改, 如果data陣列中存在id,就更新,沒有id就自動插入,第二個字斷是一個數組,可以指定更新的字斷
$data = array(
'id' => 10,
'name' => '張三',
'age' => '18',
'address' => 'beijing'
);
// 插入
$this->save($data);
// 更新
$data = array(
'id' => 10,
'name' => '張三',
'age' => '18',
'address' => 'beijing'
);
$this->save($data);
}
/**
*更新前置操作
*呼叫update方法之前呼叫
*/
public function beforeUpdate()
{
}
/**
*
* 刪除一條記錄
* return bool
*/
public function deleteSecord(){
$userTest = $this->findFirst(9);
return $userTest->delete();
}
}