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');
DB::table('tb')->where('cat', 1)->pluck('col');


三.Eloquent ORM(自己就是查詢構建器)
1.insert(也能夠使用insert方法插入一個數組到數據庫,但不會觸發事件)

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

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

create和save的區別是
a.create的參數接受的一個字段數組,save也能夠接受一個數組,可是隻是用來指定timestamps的值
b.create返回的是一個model,save只返回true或false

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

帶where而且只更新指定字段,和查詢構建器同樣
$model = TbModel::first(1);
$model->where('time', today())->update(['delayed'=>1]);

save沒法和where共用,它是根據主鍵來保存的;保存受影響的字段;

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

4.select
#多條
TbModel::all();//不能帶where
TbModel::where('cat', 1)->get(); //能夠帶where

#單條
TbModel::find(1); // 利用主鍵取回
若是查詢條件帶where,並且不是主鍵,則使用first
TbModel::where('time', today())->first();
  
相關文章
相關標籤/搜索