Laravel所自帶的Eloquent ORM是一個優(yōu)美、簡潔的ActiveRecord類,用來實(shí)現(xiàn)數(shù)據(jù)庫操作
每個數(shù)據(jù)表都有一個與之對應(yīng)的“模型”,用于和數(shù)據(jù)表交互。MVC架構(gòu)中,Controller不是直接去數(shù)據(jù)庫中取數(shù)據(jù),而是先定義好Model,然后Controller取Model取數(shù)據(jù)的。
建立模型
use Illuminate\Datebase\Eloquent\Model;
class Student extends Model
{
// 指定表名
protected $table = 'student';
// 指定主鍵
protected $primaryKey = 'id';
}
ORM中的新增、自定義時(shí)間戳及批量賦值
兩種方式:
通過模型新增數(shù)據(jù)(設(shè)計(jì)到自定義時(shí)間戳)
public function create()
{
// 使用模型新增數(shù)據(jù)
$student = new Student();
$student->name = 'ck';
$student->age = 18;
$student->save();
}
使用模型的Create方法新增數(shù)據(jù)(涉及到批量賦值)
$student = Student::create(
['name' => 'ck', 'age' => 18];
);
需要指定允許批量賦值的字段
protected $fillable = ['name', 'age'];
使用ORM修改數(shù)據(jù)
兩種方式
通過模型更新
public function update()
{
$student = Student::find(1);
$studnet->name = 'ck';
$student->save();
}
結(jié)合查詢語句批量更新
public function update()
{
$num = Student::where('id', '=', 1)->update(
['age' => 41]
);
}
使用ORM刪除數(shù)據(jù)
三種方式
通過模型刪除
public function modelDelete()
{
$student = Student::find(1);
$student->delete();
}
通過主鍵值刪除
public function deleteKey
{
$num = Student::destroy(1,2);
}
根據(jù)指定條件刪除
public function conditionDelete()
{
Student::where('id', '=', 1)->delete();
}