Laravel 數據庫操做之Eloquent ORM模型

//模型中的相關代碼
namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model{
//默認對應的是模型複數,即students,若是不是,須要本身指定表名
protected $table = 'student';//指定表名

//默認主鍵是id,若是不是,須要指定
protected $primaryKey = 'id';

//自動維護時間戳
public $timestamps = true;

protected function getDateFormat()
{
return time();
}

//不格式化時間戳
protected function asDateTime($val)
{
return $val;
}

//指定容許批量賦值的字段
protected $fillable = ['name','age'];

//指定不容許批量賦值的字段
protected $guarded = ['name','age'];

}


//控制器的相關代碼
//orm 使用模型查詢

public function orm1(){

//all().返回模型的對象
$student = Student::all();

//find()
$student = Student::find(100);

//findOrFail(),查找不到就報錯
$student = Student::findOrFail(100);

//get()
$student = Student::get();

//first()
$student = Student::where('id','>',10)
->orderBy('age','desc')
->first();
}


//orm 使用模型查詢
public function orm2(){
//使用模型新增數據
$student = new Student();
$student->name = 'hello';
$student->age = 'hello';
$bool = $student->save();
var_dump($bool);

//格式化日期
$student = Student::find(1);
echo date('Y-m-d H:i:s',$student->addtime);

//使用模型的create方法新增數據,
$student = Student::create(['name'=>'haha','age'=>10]);

//firstOrCreate,先查找,若沒有則新增
$student = Student::firstOrCreate(['name'=>'haha']);

//firstOrNew,先查找,若沒有則返回實例,須要自行調用save新增
$student = Student::firstOrNew(['name'=>'haha']);
$bool = $student->save();

//經過模型更新數據
$student = Student::find(10);
$student->name = 'happy';
$bool = $student->save();
var_dump($bool);

//批量更新,返回行數
$num = Student::where('id','>',10)->update(
['age'=>20]
);
var_dump($num);

//經過模型刪除,不存在會報錯
$student = Student::find(10);
$bool = $student->delete();
var_dump($bool);

//經過主鍵刪除
$num=Student::destroy(10);
var_dump($num);
$num=Student::destroy([10,11,20]);
var_dump($num);

$num=Student::where('id','>',20)->delete();
var_dump($num);

}
相關文章
相關標籤/搜索