@Chiang
2019-12-13T15:09:10.000000Z
字数 1282
阅读 559
Laravel
$user = DB::connection('foo')->select(...);
$pdo = DB::connection()->getPdo();
// select
$users = DB::select('select * from users where active = ?',[1]);
$users = DB::select('select * form users where id = :id',['i'=>1]);
// insert
DB::insert('insert into users (id,name) values (?,?)',[1,'fazhan']);
// update
$affected = update('update users set votes = 100 where name = ?',['fazhan']);
// delete
$deleted = DB::delete('delete from users');
// statement
DB::statement('drop table users');
如果你希望能够监控到程序执行的每一条 SQL 语句,那么你可以使用 listen 方法。这个方法对于记录查询或调试非常有用。您可以将查询侦听器注册到一个
服务提供者
<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* 启动应用服务。
*
* @return void
*/
public function boot()
{
DB::listen(function ($query) {
// $query->sql
// $query->bindings
// $query->time
});
}
/**
* 注册服务提供者。
*
* @return void
*/
public function register()
{
//
}
}
DB::transaction(function(){
DB::table('users')->update(['votes'=>1]);
DB::table('posts')->delete();
});
DB::transaction(function(){
DB::table('users')->update(['votes'=>1]);
DB::table('posts')->delete();
},5);
// 事务开始
DB::beginTransaction();
// 事务回滚
DB::rollBack();
// 事务提交
DB::commit();
手动操作事务可以配合异常捕获
try {
//...
} catch (Exception $e) {
//...
}