控制器方法:
//Eloquent ORM的使用: public function orm1() { //all() /*$students=Student::all(); dd($students); */ //find(); /*$student=Student::find(1001); dd($student);*/ //findOrFail() /*$student=Student::findOrFail(1008); dd($student);*/ //查詢構造器在ORM中的使用: /*$students=Student::get(); dd($students);*/ //first() /*$students=Student::where('id','>','1001') ->orderBy('age','desc') ->first(); dd($students);*/ //chunk() /*Student::chunk(2,function ($students){ var_dump($students); });*/ //查詢構造器中的聚合函數: //count /*$num=Student::count(); var_dump($num);*/ //max() /*$max=Student::where('id','>',1001)->max('age'); var_dump($max);*/ } //ORM中的新增、自定義時間戳及批量賦值: public function orm2() { //使用模型新增數據: /*$student = new Student(); $student->name = "笑笑"; $student->age = 22; $bool =$student->save(); dd($student);*/ /*$student = Student::find(1007); echo $student->created_at;*/ /*$student = Student::find(1007); //自己格式化時間戳 echo date('Y-m-d H:i:s', $student->created_at);*/ //使用模型的Create方法新增數據: /*$student=Student::create( ['name'=>'imooc','age'=>18] ); var_dump($student);*/ //firstOrCreate() 以屬性查找用戶,若沒有則新增,並取得新的實例: /*$student= Student::firstOrCreate( ['name'=>'imoocs'] ); dd($student);*/ //firstOrNew()以屬性查找用戶,若沒有則建立新的實例。需要保存的,自己調用save $student = Student::firstOrNew( ['name' => 'imoocs789'] ); $bool = $student->save(); dd($bool); } //ORM更新數據: public function orm3() { //通過模型更新數據:( save保存方法不可行) /*$student = Student::find(1001); $student->name = 'kitty'; $bool=$student->save(); dd($bool);*/ //結合查詢語句,批量更新: /*$num=Student::where('id','>',1005)->update( ['age'=>41] ); var_dump($num);*/ } //使用Eloquent ORM刪除數據: public function orm4(){ //通過模型刪除數據: /*$student=Student::find(1008); $bool=$student->delete(); var_dump($bool);*/ //通過主鍵刪除: // /*$num=Student::destroy(1010);*/ //刪除兩條數據: /*$num=Student::destroy(1007,1009);*/ /*$num=Student::destroy([1007,1009]); var_dump($num);*/ //通過條件刪除: /* $num=Student::where('id','>',1004)->delete(); var_dump($num);*/ }
模型的設置:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { //指定表名: protected $table="student"; //指定id protected $primaryKey="id"; //指定允許批量的字段: protected $fillable=['name','age']; //指定不允許批量賦值的字段 protected $guarded=[]; //自動維護時間戳: public $timestamps=true; //返回當前時間的時間戳,進入數據庫,輸出時,可以輸出格式化好的時間。 protected function getDateFormat() { return time(); } //設置他之后,返回的就是數據表中的時間戳了。 protected function asDateTime($value) { return $value; } }