php原生sql
1.查询
<?php
namespace App\Http\Controllers;
use DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* @return Response
*/
public function index()
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
或者值的绑定方式
$results = DB::select('select * from users where id = :id', ['id' => 1]);
2.插入
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
3.跟新
返回的是影响的行数
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
4.删除
返回删除的行数
$deleted = DB::delete('delete from users');
5.对于没有返回值的操作,可以共用
DB::statement('drop table users');
2.事务
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
或者手动控制事务
DB::beginTransaction();
DB::rollBack();
DB::commit();
3.监听方法
<?php
namespace App\Providers;
use DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
DB::listen(function($sql, $bindings, $time) {
//
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}