【发布时间】:2014-07-10 14:36:31
【问题描述】:
我正在开发一个使用 PHP Active Record 的项目,并且对它很陌生,我真的开始喜欢它了。所有对象都是 ActiveRecord 模型的扩展
class User extends Model {
}
class Item extends Model {
}
.
.
.
现在我的代码将具有与此类似的内容(users 表包含属于用户的项目的计数,并且 items 表包含项目)。
$user = User::find_by_id($id);
$user->num_items++;
$item = new Item();
//Do stuff with the item
$user->save();
$item->save();
现在我担心理论上的可能性,即当网站受到重击时,某些东西会损坏或数据库被拆除以进行维护(是的,这些事情与我有关)。由于理论上这些语句不在事务中:
$user->save();
//User table is updated successfully
//----- MySQL goes Down Here -------/
$item->save(); //This won't run, now the user's table may say he has 4 items but he only has 3 since the last one didn't get inserted
我希望能够将用户和项目一起保存,如果其中一个失败,它们会回滚。我知道如何在手动 MySQL 中执行此操作,但这违背了使用 ORM 的目的。
【问题讨论】:
标签: php mysql activerecord transactions