{ echo $message, "\n";
}
} else {
echo "The robot was deleted successfully!";
}
}
也可以使用遍历的方式删除多个条目的数据:
$robots = Robots::find(array(
array("type" => "mechanical")
));
foreach ($robots as $robot) {
if ($robot->delete() == false) {
echo "Sorry, we can't delete the robot right now: \n";
foreach ($robot->getMessages() as $message) {
echo $message, "\n";
}
} else {
echo "The robot was deleted successfully!";
}
}
当删除操作执行时我们可以执行如下事件,以实现定制业务逻辑的目的:
| 操作 |
名称 |
是否可停止 |
解释 |
| 删除 |
beforeDelete |
是 |
删除之前执行 |
| 删除 |
afterDelete |
否 |
删除之后执行 |
验证失败事件(Validation Failed Events)?
验证失败时依据不同的情形下列事件会触发:
| 操作 |
名称 |
解释 |
| 插入和或更新 |
notSave |
当插入/更新操作失败时触 |
| 插入删除或更新 |
onValidationFails |
当数据操作失败时触发 |
固有 Id 和 用户主键(Implicit Ids vs. User Primary Keys)?
默认Phalcon\Mvc\Collection会使用MongoIds_来产生_id.如果用户想自定义主键也可以只需:
class Robots extends Phalcon\Mvc\Collection
{
public function initialize()
{
$this->useImplicitObjectIds(false);
}
}
设置多个数据库(Setting multiple databases)?
Phalcon中,所有的模可以只属于一个数据库或是每个模型有一个数据。事实上当 Phalcon\Mvc\Collection 试图连接数据库时 Phalcon会从DI中取名为mongo的服务。当然我们可在模型的initialize方法中进行连接设置:
// This service returns a mongo database at 192.168.1.100
$di->set('mongo1', function() {
$mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
return $mongo->selectDb("management");
}, true);
// This service returns a mongo database at localhost
$di->set('mongo2', function() {
$mongo = new Mongo("mongodb://localhost");
return $mongo->selectDb("invoicing");
}, true);
然后在初始化方法,我们定义了模型的连接:
class Robots extends \Phalcon\Mvc\Collection
{
public function initialize()
{
$this->setConnectionService('mongo1');
}
}
注入服务到模型(Injecting services into Models)?
我们可能需要在模型内使用应用的服务,下面的例子中展示了如何去做:
class Robots extends \Phalcon\Mvc\Collection
{
public function notSave()
{
// Obtain the flash service from the DI container
$flash = $this->getDI()->getShared('flash');
// Show validation messages
foreach ($this->getMessages() as $message){
$flash->error((string) $message);
}
}
}
notSave事件在创建和更新失败时触发。我们使用flash服务来处理验证信息。如此做我们无需在每次保存后打印消息出来。