首页 > 代码库 > DB门面,查询构建器,Eloquent ORM三者的CURD

DB门面,查询构建器,Eloquent ORM三者的CURD

一.DB门面
1.insert
DB::insert(‘insert into table(`name`) value(?)‘, [‘test‘]);

2.update
DB::update(‘update into table set name=? where id=?‘, [‘test‘, 10]);

3.delete
DB::delete(‘delete from tb where id=?‘, [1]);

4.select
DB:select(‘select * from tb‘);


二.查询构建器
1.insert
DB::table(‘tb‘)->insert([‘name‘ => ‘test‘]);

2.update
DB::table(‘tb‘)->where(‘id‘, 1)->update([‘name‘ => ‘test‘]);

3.delete
DB::table(‘tb‘)->where(‘id‘, 1)->delete();

4.select
# 多条
DB::table(‘tb‘)->where(‘cat‘, 1)->orWhere(function($query){
		return $query->where(‘vote‘, ‘>‘, 1);
	})->orderBy(‘id‘, ‘DESC‘)->select(‘name‘)->skip(5)->take(10)->get();

#一条
DB::table(‘tb‘)->where(‘cat‘, 1)->first();

#一列
DB::table(‘tb‘)->where(‘cat‘, 1)->value(‘col‘);


三.Eloquent ORM(本身就是查询构建器)
1.insert

$model = new TbModel;
$model->name = ‘test‘;
$model->save();

使用create,但需要模型限定fillable或guarded
TbModel::create([‘name‘ => ‘test‘]);

2.update
$model = TbModel::first(1);
$model->name = ‘test‘;
$model->save();

带where并且只更新指定字段,和查询构建器一样
$model = TbModel::first(1);
$model->where(‘time‘, today())->update([‘delayed‘=>1]);

3.delete
TbModel::first(1)->delete();
TbModel::destory(1);
Flight::where(‘id‘, 1)->delete();

4.select
#多条
TbModel::all();
TbModel::get();

#单条
TbModel::find(1); // 利用主键取回
如果查询条件带where,而且不是主键,则使用first
TbModel::where(‘time‘, today())->first();

  

DB门面,查询构建器,Eloquent ORM三者的CURD