# 使用模型(Working with Models)
模型代表了應用程序中的信息(數據)和處理數據的規則。模型主要用于管理與相應數據庫表進行交互的規則。 大多數情況中,在應用程序中,數據庫中每個表將對應一個模型。 應用程序中的大部分業務邏輯都將集中在模型里。
[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)是 Phalcon 應用程序中所有模型的基類。它保證了數據庫的獨立性,基本的 CURD 操作, 高級的查詢功能,多表關聯等功能。[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)不需要直接使用 SQL 語句,因為它的轉換方法,會動態的調用相應的數據庫引擎進行處理。
> 模型是數據庫的高級抽象層。如果您想進行低層次的數據庫操作,您可以查看[Phalcon\\Db](http://docs.iphalcon.cn/api/Phalcon_Db.html)組件文檔。
## 創建模型
模型是一個繼承自[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)的一個類。時它的類名必須符合駝峰命名法:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
}
~~~
> 如果使用 PHP 5.4/5.5 建議在模型中預先定義好所有的列,這樣可以減少模型內存的開銷以及內存分配。
默認情況下,模型 “Store\\Toys\\RobotParts” 對應的是數據庫表 “robot\_parts”, 如果想映射到其他數據庫表,可以使用`setSource()`方法:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
public function initialize()
{
$this->setSource("toys_robot_parts");
}
}
~~~
模型 RobotParts 現在映射到了 “toys\_robot\_parts” 表。`initialize()`方法可以幫助在模型中建立自定義行為,例如指定不同的數據庫表。
`initialize()`方法在請求期間僅會被調用一次,目的是為應用中所有該模型的實例進行初始化。如果需要為每一個實例在創建的時候單獨進行初始化, 可以使用`onConstruct()`事件:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
public function onConstruct()
{
// ...
}
}
~~~
### 公共屬性對比設置與取值 Setters/Getters(Public properties vs. Setters/Getters)
模型可以通過公共屬性的方式實現,意味著模型的所有屬性在實例化該模型的地方可以無限制的讀取和更新。
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $price;
}
~~~
通過使用 getters/setters 方法,可以控制哪些屬性可以公開訪問,并且對屬性值執行不同的形式的轉換,同時可以保存在模型中的數據添加相應的驗證規則。
~~~
<?php
namespace Store\Toys;
use InvalidArgumentException;
use Phalcon\Mvc\Model;
class Robots extends Model
{
protected $id;
protected $name;
protected $price;
public function getId()
{
return $this->id;
}
public function setName($name)
{
// The name is too short?
if (strlen($name) < 10) {
throw new InvalidArgumentException(
"The name is too short"
);
}
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setPrice($price)
{
// Negative prices aren't allowed
if ($price < 0) {
throw new InvalidArgumentException(
"Price can't be negative"
);
}
$this->price = $price;
}
public function getPrice()
{
// Convert the value to double before be used
return (double) $this->price;
}
}
~~~
公共屬性的方式可以在開發中降低復雜度。而 getters/setters 的實現方式可以顯著的增強應用的可測試性、擴展性和可維護性。 開發人員可以自己決定哪一種策略更加適合自己開發的應用。ORM同時兼容這兩種方法。
> Underscores in property names can be problematic when using getters and setters.
If you use underscores in your property names, you must still use camel case in your getter/setter declarations for use with magic methods. (e.g. $model->getPropertyName instead of $model->getProperty\_name, $model->findByPropertyName instead of $model->findByProperty\_name, etc.). As much of the system expects camel case, and underscores are commonly removed, it is recommended to name your properties in the manner shown throughout the documentation. You can use a column map (as described above) to ensure proper mapping of your properties to their database counterparts.
## 理解記錄對象(Understanding Records To Objects)
每個模型的實例對應一條數據表中的記錄。可以方便的通過讀取對象的屬性來訪問相應的數據。比如, 一個表 “robots” 有如下數據:
~~~
mysql> select * from robots;
+----+------------+------------+------+
| id | name | type | year |
+----+------------+------------+------+
| 1 | Robotina | mechanical | 1972 |
| 2 | Astro Boy | mechanical | 1952 |
| 3 | Terminator | cyborg | 2029 |
+----+------------+------------+------+
3 rows in set (0.00 sec)
~~~
你可以通過主鍵找到某一條記錄并且打印它的名稱:
~~~
<?php
use Store\Toys\Robots;
// Find record with id = 3
$robot = Robots::findFirst(3);
// Prints "Terminator"
echo $robot->name;
~~~
一旦記錄被加載到內存中之后,你可以修改它的數據并保存所做的修改:
~~~
<?php
use Store\Toys\Robots;
$robot = Robots::findFirst(3);
$robot->name = "RoboCop";
$robot->save();
~~~
如上所示,不需要寫任何SQL語句。[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)為web應用提供了高層數據庫抽象。
## 查找記錄(Finding Records)
[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)為數據查詢提供了多種方法。下面的例子將演示如何從一個模型中查找一條或者多條記錄:
~~~
<?php
use Store\Toys\Robots;
// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";
// How many mechanical robots are there?
$robots = Robots::find("type = 'mechanical'");
echo "There are ", count($robots), "\n";
// Get and print virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// Get first 100 virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
"limit" => 100,
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
~~~
> 如果需要通過外部數據(比如用戶輸入)或變量來查詢記錄,則必須要用`Binding Parameters`(綁定參數)的方式來防止SQL注入.
你可以使用`findFirst()`方法獲取第一條符合查詢條件的結果:
~~~
<?php
use Store\Toys\Robots;
// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";
// What's the first mechanical robot in robots table?
$robot = Robots::findFirst("type = 'mechanical'");
echo "The first mechanical robot name is ", $robot->name, "\n";
// Get first virtual robot ordered by name
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual robot name is ", $robot->name, "\n";
~~~
`find()`和`findFirst()`方法都接受關聯數組作為查詢條件:
~~~
<?php
use Store\Toys\Robots;
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name DESC",
"limit" => 30,
]
);
$robots = Robots::find(
[
"conditions" => "type = ?1",
"bind" => [
1 => "virtual",
]
]
);
~~~
可用的查詢選項如下:
| 參數 | 描述 | 舉例 |
| --- | --- | --- |
| conditions | 查詢操作的搜索條件。用于提取只有那些滿足指定條件的記錄。默認情況下[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)假定第一個參數就是查詢條件。 | `"conditions"=>"nameLIKE'steve%'"` |
| columns | 只返回指定的字段,而不是模型所有的字段。 當用這個選項時,返回的是一個不完整的對象。 | `"columns"=>"id,name"` |
| bind | 綁定與選項一起使用,通過替換占位符以及轉義字段值從而增加安全性。 | `"bind"=>["status"=>"A","type"=>"some-time"]` |
| bindTypes | 當綁定參數時,可以使用這個參數為綁定參數定義額外的類型限制從而更加增強安全性。 | `"bindTypes"=>[Column::BIND_PARAM_STR,Column::BIND_PARAM_INT]` |
| order | 用于結果排序。使用一個或者多個字段,逗號分隔。 | `"order"=>"nameDESC,status"` |
| limit | 限制查詢結果的數量在一定范圍內。 | `"limit"=>10` |
| offset | Offset the results of the query by a certain amount | `"offset"=>5` |
| group | 從多條記錄中獲取數據并且根據一個或多個字段對結果進行分組。 | `"group"=>"name,status"` |
| for\_update | 通過這個選項,[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)讀取最新的可用數據,并且為讀到的每條記錄設置獨占鎖。 | `"for_update"=>true` |
| shared\_lock | 通過這個選項,[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)讀取最新的可用數據,并且為讀到的每條記錄設置共享鎖。 | `"shared_lock"=>true` |
| cache | 緩存結果集,減少了連續訪問數據庫。 | `"cache"=>["lifetime"=>3600,"key"=>"my-find-key"]` |
| hydration | Sets the hydration strategy to represent each returned record in the result | `"hydration"=>Resultset::HYDRATE_OBJECTS` |
如果你愿意,除了使用數組作為查詢參數外,還可以通過一種面向對象的方式來創建查詢:
~~~
<?php
use Store\Toys\Robots;
$robots = Robots::query()
->where("type = :type:")
->andWhere("year < 2000")
->bind(["type" => "mechanical"])
->order("name")
->execute();
~~~
靜態方法`query()`返回一個對IDE自動完成友好的[Phalcon\\Mvc\\Model\\Criteria](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_Criteria.html)對象。
所有查詢在內部都以[PHQL](http://docs.iphalcon.cn/reference/phql.html)查詢的方式處理。PHQL是一個高層的、面向對象的類SQL語言。通過PHQL語言你可以使用更多的比如join其他模型、定義分組、添加聚集等特性。
最后,還有一個`findFirstBy<property-name>()`方法。這個方法擴展了前面提及的`findFirst()`方法。它允許您利用方法名中的屬性名稱,通過將要搜索的該字段的內容作為參數傳給它,來快速從一個表執行檢索操作。
還是用上面用過的 Robots 模型來舉例說明:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $price;
}
~~~
我們這里有3個屬性:`$id`,`$name`和`$price`。因此,我們以想要查詢第一個名稱為 ‘Terminator’ 的記錄為例,可以這樣寫:
~~~
<?php
use Store\Toys\Robots;
$name = "Terminator";
$robot = Robots::findFirstByName($name);
if ($robot) {
echo "The first robot with the name " . $name . " cost " . $robot->price . ".";
} else {
echo "There were no robots found in our table with the name " . $name . ".";
}
~~~
請注意我們在方法調用中用的是 ‘Name’,并向它傳遞了變量`$name`,`$name`的值就是我們想要找的記錄的名稱。另外注意,當我們的查詢找到了符合的記錄后,這個記錄的其他屬性也都是可用的。
### 模型結果集(Model Resultsets)
`findFirst()`方法直接返回一個被調用對象的實例(如果有結果返回的話),而`find()`方法返回一個[Phalcon\\Mvc\\Model\\Resultset\\Simple](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_Resultset_Simple.html)對象。這個對象也封裝進了所有結果集的功能,比如遍歷、查找特定的記錄、統計等等。
這些對象比一般數組功能更強大。最大的特點是[Phalcon\\Mvc\\Model\\Resultset](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_Resultset.html)每時每刻只有一個結果在內存中。這對操作大數據量時的內存管理相當有幫助。
~~~
<?php
use Store\Toys\Robots;
// Get all robots
$robots = Robots::find();
// Traversing with a foreach
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// Traversing with a while
$robots->rewind();
while ($robots->valid()) {
$robot = $robots->current();
echo $robot->name, "\n";
$robots->next();
}
// Count the resultset
echo count($robots);
// Alternative way to count the resultset
echo $robots->count();
// Move the internal cursor to the third robot
$robots->seek(2);
$robot = $robots->current();
// Access a robot by its position in the resultset
$robot = $robots[5];
// Check if there is a record in certain position
if (isset($robots[3])) {
$robot = $robots[3];
}
// Get the first record in the resultset
$robot = $robots->getFirst();
// Get the last record
$robot = $robots->getLast();
~~~
Phalcon 的結果集模擬了可滾動的游標,你可以通過位置,或者內部指針去訪問任何一條特定的記錄。注意有一些數據庫系統不支持滾動游標,這就使得查詢會被重復執行, 以便回放光標到最開始的位置,然后獲得相應的記錄。類似地,如果多次遍歷結果集,那么必須執行相同的查詢次數。
將大數據量的查詢結果存儲在內存會消耗很多資源,正因為如此,分成每32行一塊從數據庫中獲得結果集,以減少重復執行查詢請求的次數,在一些情況下也節省內存。
注意結果集可以序列化后保存在一個后端緩存里面。[Phalcon\\Cache](http://docs.iphalcon.cn/reference/cache.html)可以用來實現這個。但是,序列化數據會導致[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)將從數據庫檢索到的所有數據以一個數組的方式保存,因此在這樣執行的地方會消耗更多的內存。
~~~
<?php
// Query all records from model parts
$parts = Parts::find();
// Store the resultset into a file
file_put_contents(
"cache.txt",
serialize($parts)
);
// Get parts from file
$parts = unserialize(
file_get_contents("cache.txt")
);
// Traverse the parts
foreach ($parts as $part) {
echo $part->id;
}
~~~
### 過濾結果集(Filtering Resultsets)
過濾數據最有效的方法是設置一些查詢條件,數據庫會利用表的索引快速返回數據。Phalcon 額外的允許你通過任何數據庫不支持的方式過濾數據。
~~~
<?php
$customers = Customers::find();
$customers = $customers->filter(
function ($customer) {
// Return only customers with a valid e-mail
if (filter_var($customer->email, FILTER_VALIDATE_EMAIL)) {
return $customer;
}
}
);
~~~
### 綁定參數(Binding Parameters)
在[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)中也支持綁定參數。即使使用綁定參數對性能有一點很小的影響,還是強烈建議您使用這種方法,以消除代碼受SQL注入攻擊的可能性。 綁定參數支持字符串和整數占位符。實現方法如下:
~~~
<?php
use Store\Toys\Robots;
// Query robots binding parameters with string placeholders
// Parameters whose keys are the same as placeholders
$robots = Robots::find(
[
"name = :name: AND type = :type:",
"bind" => [
"name" => "Robotina",
"type" => "maid",
],
]
);
// Query robots binding parameters with integer placeholders
$robots = Robots::find(
[
"name = ?1 AND type = ?2",
"bind" => [
1 => "Robotina",
2 => "maid",
],
]
);
// Query robots binding parameters with both string and integer placeholders
// Parameters whose keys are the same as placeholders
$robots = Robots::find(
[
"name = :name: AND type = ?1",
"bind" => [
"name" => "Robotina",
1 => "maid",
],
]
);
~~~
如果是數字占位符,則必須把它們定義成整型(如1或者2)。若是定義為字符串型(如”1”或者”2”),則這個占位符不會被替換。
使用PDO\_的方式會自動轉義字符串。它依賴于字符集編碼,因此建議在連接參數或者數據庫配置中設置正確的字符集編碼。 若是設置錯誤的字符集編碼,在存儲數據或檢索數據時,可能會出現亂碼。
另外你可以設置參數的“bindTypes”,這允許你根據數據類型來定義參數應該如何綁定:
~~~
<?php
use Phalcon\Db\Column;
use Store\Toys\Robots;
// Bind parameters
$parameters = [
"name" => "Robotina",
"year" => 2008,
];
// Casting Types
$types = [
"name" => Column::BIND_PARAM_STR,
"year" => Column::BIND_PARAM_INT,
];
// Query robots binding parameters with string placeholders
$robots = Robots::find(
[
"name = :name: AND year = :year:",
"bind" => $parameters,
"bindTypes" => $types,
]
);
~~~
> 默認的參數綁定類型是`Phalcon\Db\Column::BIND_PARAM_STR`, 若所有字段都是string類型,則不用特意去設置參數的“bindTypes”.
如果你的綁定參數是array數組,那么數組索引必須從數字0開始:
~~~
<?php
use Store\Toys\Robots;
$array = ["a","b","c"]; // $array: [[0] => "a", [1] => "b", [2] => "c"]
unset($array[1]); // $array: [[0] => "a", [2] => "c"]
// Now we have to renumber the keys
$array = array_values($array); // $array: [[0] => "a", [1] => "c"]
$robots = Robots::find(
[
'letter IN ({letter:array})',
'bind' => [
'letter' => $array
]
]
);
~~~
> 參數綁定的方式適用于所有與查詢相關的方法,如`find()`,`findFirst()`等等, 同時也適用于與計算相關的方法,如`count()`,`sum()`,`average()`等等.
若使用如下方式,phalcon也會自動為你進行參數綁定:
~~~
<?php
use Store\Toys\Robots;
// Explicit query using bound parameters
$robots = Robots::find(
[
"name = ?0",
"bind" => [
"Ultron",
],
]
);
// Implicit query using bound parameters(隱式的參數綁定)
$robots = Robots::findByName("Ultron");
~~~
## 獲取記錄的初始化以及準備(Initializing/Preparing fetched records)
有時從數據庫中獲取了一條記錄之后,在被應用程序使用之前,需要對數據進行初始化。 你可以在模型中實現”afterFetch”方法,在模型實例化之后會執行這個方法,并將數據分配給它:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $status;
public function beforeSave()
{
// Convert the array into a string
$this->status = join(",", $this->status);
}
public function afterFetch()
{
// Convert the string to an array
$this->status = explode(",", $this->status);
}
public function afterSave()
{
// Convert the string to an array
$this->status = explode(",", $this->status);
}
}
~~~
如果使用getters/setters方法代替公共屬性的取/賦值,你能在它被調用時,對成員屬性進行初始化:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $status;
public function getStatus()
{
return explode(",", $this->status);
}
}
~~~
## 生成運算(Generating Calculations)
Calculations (or aggregations) are helpers for commonly used functions of database systems such as COUNT, SUM, MAX, MIN or AVG.[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)allows to use these functions directly from the exposed methods.
Count examples:
~~~
<?php
// How many employees are?
$rowcount = Employees::count();
// How many different areas are assigned to employees?
$rowcount = Employees::count(
[
"distinct" => "area",
]
);
// How many employees are in the Testing area?
$rowcount = Employees::count(
"area = 'Testing'"
);
// Count employees grouping results by their area
$group = Employees::count(
[
"group" => "area",
]
);
foreach ($group as $row) {
echo "There are ", $row->rowcount, " in ", $row->area;
}
// Count employees grouping by their area and ordering the result by count
$group = Employees::count(
[
"group" => "area",
"order" => "rowcount",
]
);
// Avoid SQL injections using bound parameters
$group = Employees::count(
[
"type > ?0",
"bind" => [
$type
],
]
);
~~~
Sum examples:
~~~
<?php
// How much are the salaries of all employees?
$total = Employees::sum(
[
"column" => "salary",
]
);
// How much are the salaries of all employees in the Sales area?
$total = Employees::sum(
[
"column" => "salary",
"conditions" => "area = 'Sales'",
]
);
// Generate a grouping of the salaries of each area
$group = Employees::sum(
[
"column" => "salary",
"group" => "area",
]
);
foreach ($group as $row) {
echo "The sum of salaries of the ", $row->area, " is ", $row->sumatory;
}
// Generate a grouping of the salaries of each area ordering
// salaries from higher to lower
$group = Employees::sum(
[
"column" => "salary",
"group" => "area",
"order" => "sumatory DESC",
]
);
// Avoid SQL injections using bound parameters
$group = Employees::sum(
[
"conditions" => "area > ?0",
"bind" => [
$area
],
]
);
~~~
Average examples:
~~~
<?php
// What is the average salary for all employees?
$average = Employees::average(
[
"column" => "salary",
]
);
// What is the average salary for the Sales's area employees?
$average = Employees::average(
[
"column" => "salary",
"conditions" => "area = 'Sales'",
]
);
// Avoid SQL injections using bound parameters
$average = Employees::average(
[
"column" => "age",
"conditions" => "area > ?0",
"bind" => [
$area
],
]
);
~~~
Max/Min examples:
~~~
<?php
// What is the oldest age of all employees?
$age = Employees::maximum(
[
"column" => "age",
]
);
// What is the oldest of employees from the Sales area?
$age = Employees::maximum(
[
"column" => "age",
"conditions" => "area = 'Sales'",
]
);
// What is the lowest salary of all employees?
$salary = Employees::minimum(
[
"column" => "salary",
]
);
~~~
## 創建與更新記錄(Creating/Updating Records)
The`Phalcon\Mvc\Model::save()`method allows you to create/update records according to whether they already exist in the table associated with a model. The save method is called internally by the create and update methods of[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html). For this to work as expected it is necessary to have properly defined a primary key in the entity to determine whether a record should be updated or created.
Also the method executes associated validators, virtual foreign keys and events that are defined in the model:
~~~
<?php
use Store\Toys\Robots;
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() === false) {
echo "Umh, We can't store robots right now: \n";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
} else {
echo "Great, a new robot was saved successfully!";
}
~~~
An array could be passed to “save” to avoid assign every column manually.[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)will check if there are setters implemented for the columns passed in the array giving priority to them instead of assign directly the values of the attributes:
~~~
<?php
use Store\Toys\Robots;
$robot = new Robots();
$robot->save(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
~~~
Values assigned directly or via the array of attributes are escaped/sanitized according to the related attribute data type. So you can pass an insecure array without worrying about possible SQL injections:
~~~
<?php
use Store\Toys\Robots;
$robot = new Robots();
$robot->save($_POST);
~~~
> Without precautions mass assignment could allow attackers to set any database column’s value. Only use this feature if you want to permit a user to insert/update every column in the model, even if those fields are not in the submitted form.
You can set an additional parameter in ‘save’ to set a whitelist of fields that only must taken into account when doing the mass assignment:
~~~
<?php
use Store\Toys\Robots;
$robot = new Robots();
$robot->save(
$_POST,
[
"name",
"type",
]
);
~~~
### 創建與更新結果判斷(Create/Update with Confidence)
When an application has a lot of competition, we could be expecting create a record but it is actually updated. This could happen if we use`Phalcon\Mvc\Model::save()`to persist the records in the database. If we want to be absolutely sure that a record is created or updated, we can change the`save()`call with`create()`or`update()`:
~~~
<?php
use Store\Toys\Robots;
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
// This record only must be created
if ($robot->create() === false) {
echo "Umh, We can't store robots right now: \n";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
} else {
echo "Great, a new robot was created successfully!";
}
~~~
These methods “create” and “update” also accept an array of values as parameter.
## 刪除記錄(Deleting Records)
The`Phalcon\Mvc\Model::delete()`method allows to delete a record. You can use it as follows:
~~~
<?php
use Store\Toys\Robots;
$robot = Robots::findFirst(11);
if ($robot !== false) {
if ($robot->delete() === false) {
echo "Sorry, we can't delete the robot right now: \n";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
} else {
echo "The robot was deleted successfully!";
}
}
~~~
You can also delete many records by traversing a resultset with a foreach:
~~~
<?php
use Store\Toys\Robots;
$robots = Robots::find(
"type = 'mechanical'"
);
foreach ($robots as $robot) {
if ($robot->delete() === false) {
echo "Sorry, we can't delete the robot right now: \n";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
} else {
echo "The robot was deleted successfully!";
}
}
~~~
The following events are available to define custom business rules that can be executed when a delete operation is performed:
| Operation | Name | Can stop operation? | Explanation |
| --- | --- | --- | --- |
| Deleting | beforeDelete | YES | Runs before the delete operation is made |
| Deleting | afterDelete | NO | Runs after the delete operation was made |
With the above events can also define business rules in the models:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function beforeDelete()
{
if ($this->status === "A") {
echo "The robot is active, it can't be deleted";
return false;
}
return true;
}
}
~~~
- 簡介
- 安裝
- 安裝(installlation)
- XAMPP下的安裝
- WAMP下安裝
- Nginx安裝說明
- Apache安裝說明
- Cherokee 安裝說明
- 使用 PHP 內置 web 服務器
- Phalcon 開發工具
- Linux 系統下使用 Phalcon 開發工具
- Mac OS X 系統下使用 Phalcon 開發工具
- Windows 系統下使用 Phalcon 開發工具
- 教程
- 教程 1:讓我們通過例子來學習
- 教程 2:INVO簡介
- 教程 3: 保護INVO
- 教程4: 使用CRUD
- 教程5: 定制INVO
- 教程 6: V?kuró
- 教程 7:創建簡單的 REST API
- 組件
- 依賴注入與服務定位器
- MVC架構
- 使用控制器
- 使用模型
- 模型關系
- 事件與事件管理器
- Behaviors
- 模型元數據
- 事務管理
- 驗證數據完整性
- Workingwith Models
- Phalcon查詢語言
- 緩存對象關系映射
- 對象文檔映射 ODM
- 使用視圖
- 視圖助手
- 資源文件管理
- Volt 模版引擎
- MVC 應用
- 路由
- 調度控制器
- Micro Applications
- 使用命名空間
- 事件管理器
- Request Environmen
- 返回響應
- Cookie 管理
- 生成 URL 和 路徑
- 閃存消息
- 使用 Session 存儲數據
- 過濾與清理
- 上下文編碼
- 驗證Validation
- 表單_Forms
- 讀取配置
- 分頁 Pagination
- 使用緩存提高性能
- 安全
- 加密與解密 Encryption/Decryption
- 訪問控制列表
- 多語言支持
- 類加載器 Class Autoloader
- 日志記錄_Logging
- 注釋解析器 Annotations Parser
- 命令行應用 Command Line Applications
- Images
- 隊列 Queueing
- 數據庫抽象層
- 國際化
- 數據庫遷移
- 調試應用程序
- 單元測試
- 進階技巧與延伸閱讀
- 提高性能:下一步該做什么?
- Dependency Injection Explained
- Understanding How Phalcon Applications Work
- Api
- Abstract class Phalcon\Acl