File tree Expand file tree Collapse file tree 2 files changed +40
-5
lines changed Expand file tree Collapse file tree 2 files changed +40
-5
lines changed Original file line number Diff line number Diff line change 88class apiController extends Controller {
99
1010 public function testGet ($ id ){
11- $ data = Demo::find ($ id );
12- return $ this ->response ($ data );
11+ $ table = "demo " ;
12+ $ database = new Database ($ table );
13+
14+ $ database ->beginTransaction ();
15+ $ database ->where ([ "id " => 1 ])->update ([ "author " => $ id ]);
16+ if ($ id ==1 ){
17+ sleep (10 );
18+ }
19+
20+ dump ($ database ->commit ());
21+
22+ dd (Demo::find (1 ));
1323 }
1424
1525 // ORM 查询类方法演示
@@ -142,4 +152,22 @@ public function responseDemoGet($id){
142152 // }
143153
144154 }
155+
156+ public function transactionGet ($ id ){
157+ // 事物演示,以第一行的数据作为例子(并没使用异常捕获并回滚)
158+ $ table = "demo " ;
159+ $ database = new Database ($ table );
160+ //开始事物
161+ $ database ->beginTransaction ();
162+ $ database ->where ([ "id " => 1 ])->update ([ "author " => $ id ]);
163+
164+ // 如果请求的 id 是 1,则等待 10 秒
165+ // 在这 10 秒内,可以试着用不同的 id 进行访问,结果: id 为 1 的请求在 10 秒后完成,其余请求亦是在 id 为 1 的请求完成后全部完成,可见事物起作用了(因为其他请求被阻塞了呀!事物操作具有原子性和隔离性,并常用于保持数据的一致)
166+ if ($ id ==1 ){
167+ sleep (10 );
168+ }
169+
170+ dump ($ database ->commit ());
171+ dd (Demo::find (1 ));
172+ }
145173}
Original file line number Diff line number Diff line change @@ -128,21 +128,28 @@ public function fetchAll() {
128128
129129 /**
130130 * 开始一个新的事务
131- * @uses 用于 Model->update(), Model->delete(), Model->save() 等操作的准备工作
131+ * @return boolean
132132 */
133133 public function beginTransaction () {
134- $ this ->PDOConnect ->beginTransaction ();
134+ return $ this ->PDOConnect ->beginTransaction ();
135135 }
136136
137137 /**
138138 * 提交事务
139139 * @return boolean
140- * @uses 用于 Model->update(), Model->delete(), Model->save() 等操作使 SQL 生效
141140 */
142141 public function commit () {
143142 return $ this ->PDOConnect ->commit ();
144143 }
145144
145+ /**
146+ * 回滚事务
147+ * @return boolean
148+ */
149+ public function rollBack () {
150+ return $ this ->PDOConnect ->rollBack ();
151+ }
152+
146153
147154 // ORM 数据库查询方法
148155
You can’t perform that action at this time.
0 commit comments