其實(shí)也不算坑,只是在官方文檔中未提及或開發(fā)過(guò)程中本人未注意到的點(diǎn)
1.多數(shù)據(jù)庫(kù)使用事務(wù)的坑(model指定了$connection,用的是/config/database.php里的連接)
使用DB::beginTransaction()是沒(méi)有效果的,相當(dāng)于未使用事務(wù),必須指定連接,事務(wù)才能生效
DB::connection('連接名')->beginTransaction();
DB::connection('連接名')->rollback();
DB::connection('連接名')->commit();
2.主從分離中事務(wù)的坑
在事務(wù)開始直到結(jié)束這一過(guò)程中,所有的查詢更新刪除操作都作用在主庫(kù),所以不必?fù)?dān)心在事務(wù)中的查詢會(huì)查詢到從庫(kù),也沒(méi)必要在事務(wù)中為了查詢主庫(kù)而使用onWriteConnection;
未使用事務(wù)的地方,想要讀主庫(kù)的數(shù)據(jù),可以使用onWriteConnection: Table::onWriteConnection()->find($id);
3.increment與decrement的坑
$rs1 = Order::find(41)->decrement('shipping_fee', 0);
echo '$rs1 = '.$rs1.' ';
$rs2 = Order::find(41)->decrement('order_amount', 0);
echo '$rs2 = '.$rs2.' ';
運(yùn)行結(jié)果:$rs1 = 1 $rs2 = 0
原因分析:查看這兩行代碼執(zhí)行的真實(shí)sql語(yǔ)句:
update orders set shipping_fee = shipping_fee - 0, updated_at = '2017-08-03 10:10:25' where id = '41'
update orders set order_amount = order_amount - 0, updated_at = '2017-08-03 10:10:25' where id = '41'
結(jié)論:因?yàn)槭褂昧薼aravel時(shí)間自動(dòng)更新的功能,而且更新的是同一條數(shù)據(jù),updated_at為最新時(shí)間,第一條語(yǔ)句執(zhí)行返回條數(shù)1,而第二條的updated_at跟第一條一樣,返回的更新條數(shù)就為0了。