Home  >  Article  >  Backend Development  >  深入解析ThinkPHP框架关联模型实现(用PHP怎么确保事务一致性)

深入解析ThinkPHP框架关联模型实现(用PHP怎么确保事务一致性)

WBOY
WBOYOriginal
2016-06-13 12:49:551065browse

深入解析ThinkPHP框架关联模型实现(用PHP如何确保事务一致性)

背景:

ThinkPHP版本:3.0

当Mysql表引擎不支持事务的时候,如何确保2条以上的数据事务的一致性?

ThinkPHP是有关联模型的,因此,我深入研究了一下

环境:

两张表

User表:'


userRole表


userRole表里的user_id就是User表的主id

非常简单的一张表

然后接下来配置UserModel.class.php




配置都好了.接下来写action方法

public function add(){
		$data['username']='zpass';
		$data['password']='password';
		$data['email']='email';
		$rs=D('User')->relation(true)->add($data);
		dump($rs);
	}

开始执行

实验

最开始执行add方法.

在relation下查找,木有add方法.但是有__call方法.不过不会执行,因为add方法是存在的,是继承Model.class.php,所以这个add方法很简单,肯定就先执行Model.class.php方法

用户表被插入记录了

接下来,进行了_after_insert方法

这个方法在Moel.class.php里是空方法,不干任何事

但是在relationModel.class.php里,被重载了,于是执行了relationModel.class.php里的_after_insert方法.

这个方法先判断是否存在有定义关联模型,有定义就执行,然后继续插入userRole表里去.

结论

ThinkPHP的关联模型也无法保证两个表的事务的一致性.我试过了,当不填写userRole表的时候,就会只插入了User表数据,userRole表没有,则只能保证,当user表没有的时候.,userRole表也不会有.

关于PHP来实现类似Mysql事务的方法,其实是没有的,或者说我暂时还没找到.目前比较不错的方法就是当第二个sql执行失败的时候,倒回去删除第一条.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn