Thinkphp5.0 的使用模型Model查詢
一、查詢多條記錄
獲取多個數據可以使用:select()方法和all()方法。
示例一:使用all()方法。
//(1)篩選條件使用閉包函數 $res = User::all(function($query){ $query->where('id','>',0)->field('id,name,email'); }); foreach($res as $val){ dump($val->toArray()); } //(2)篩選條件使用where()方法 $res = User::where('id','>',0)->field('id,name,email')->all(); //致命錯誤: Call to undefined method app\index\controller\User::all()
示例二:使用select()方法。
//(1)篩選條件使用where() $res = User::where('id','>',0)->field('id,name,email')->select(); foreach($res as $val){ dump($val->toArray()); } //(2)篩選條件使用閉包函數 $res = User::select(function($query){ $query->where('id','>',0)->field('id,name,email'); }); foreach($res as $val){ dump($val->toArray()); }
1、注意結果格式:
外層是數組,里層包含多個查詢出來的對象
不能直接使用toArray(),需要遍歷
2、使用all()方法時,不能使用where等方法。
二、查詢一條記錄
獲取多個數據可以使用:find()方法和get()方法。
示例一:使用find()方法。
//(1)篩選條件使用閉包函數 $res = User::find(function($query){ $query->where('name','=','zhang san'); }); dump($res->toArray()); //(2)篩選條件使用where $res = User::where('name','=','zhang san')->find(); dump($res->toArray());
示例二:使用get()方法。
//(1)篩選條件使用閉包函數 $res = User::get(function($query){ $query->where('name','=','zhang san'); }); dump($res->toArray()); //(2)錯誤方式:篩選條件使用where()方法, $res = User::where('name','=','zhang san')->get(); dump($res->toArray()); //報錯:method not exist:think\db\Query->get //get()方式只能使用閉包形式。
三、查詢一個字段
使用value()方法
$email = User::where('name','=','zhang san')->value('email'); dump($email);
四、查詢列數據
使用column()方法:
//獲取name字段這一列 $res = User::where('id','>',0)->column('name'); dump($res); //獲取name字段這一列,並且以id字段作為索引 $res = User::where('id','>',0)->column('id,name'); dump($res); //獲取name字段這一列,並且以id字段作為索引 $res = User::where('id','>',0)->column('name','id'); dump($res); //獲取id,name,email字段這三列,並且以id字段作為索引 $res = User::where('id','>',0)->column('name,email','id'); dump($res);