Eloquent ORM簡介

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();
}

參考:https://www.imooc.com/video/12509

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,267評論 25 708
  • 去年的這個時(shí)候開始培訓(xùn),到現(xiàn)在差不多一年的時(shí)間了。不知道別的公司是怎么去考核績效的,所以只能按照我們公司的來說。 ...
    方舟舟閱讀 46,586評論 1 3
  • 顯示點(diǎn)號開頭的文件: 取消:
    何幻閱讀 364評論 0 0
  • 夜把花悄悄地開放了,卻讓白日去領(lǐng)受謝詞?!└?duì)?1 刷朋友圈刷出一條消息,讓我小小的吃驚了一下。一位朋友說:“...
    一丈月光閱讀 486評論 0 6
  • 我們很習(xí)慣地對身邊的一些現(xiàn)象產(chǎn)生鄙夷的評價(jià)。這不,在小區(qū)樓下公園里,東家、西家開始拉家常了。 “小區(qū)最近搬來了一個...
    林小哭的世界閱讀 824評論 0 0

友情鏈接更多精彩內(nèi)容