laravel:mysql使用事务(10.27.0)
一,参考文档:
https://learnku.com/docs/laravel/10.x/database/14882#09ddab
二,php代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use App\extend\result\Result; use App\Models\News; use Illuminate\Support\Facades\DB; class NewsController extends Controller { //启用事务 public function trans(Request $request ) { //启动事务 DB::beginTransaction(); $model = new News(); try { //insert $row1 = [ 'title' => '1title' , 'url' => '1url' ]; $model ->add( $row1 ); //news_id为1的主键记录已存在,会引发异常 $row2 = [ 'news_id' =>1, 'title' => '2title' , 'url' => '2url' ]; $model ->add( $row2 ); //commit DB::commit(); return '已提交' ; } catch (\Throwable $e ) { //回滚 DB::rollback(); return '已回滚' ; } } |
三,测试效果:
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/19/laravel-mysql-shi-yong-shi-wu/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0