定義Eloquent模型
模型通常放在app/models
目錄中,但是您可以自由地把它們放在任何地方,只要它能根據您的composer.json
檔案自動載入。除非顯示地指定表名,Eloquent預設情況下將模型類名的小寫,複數形式作為表名。如我們定義的模型為Game
,那麼它將操作games
資料表。
<?php
// app/models/Game.php
classGameextendsEloquent
{
//
}
然後就可以使用該模型
Route::get('/',function()
{
$game =newGame;
$game->name ='Assassins Creed';
$game->description ='Assassins VS templars.';
$game->save();
});
這是會提示錯誤,因為模型預設每個表建立時都有$table->timestamps();
,所以你需要為表新增這兩個欄位或是在模型中關閉
public $timestamps =false;
你可以為模型指定資料表
public $table ='gamezilla_roar';
Eloquent 將假設每張表有一個名為 id 的主鍵。您可以定義 primaryKey 屬性來覆蓋這個約定。同樣,您可以定義一個 connection 屬性來覆蓋在使用這個模型時所用的資料庫連線。
讀取模型資料
獲取所有所有記錄
$games =Game::all();
根據主鍵獲取一條記錄
$games =Game::fine(1);
[查詢構建器] 中適用的函式在 Eloquent 模型的查詢中同樣適用。具體參考官方API手冊
根據主鍵獲取一條記錄或者丟擲一個異常
$model =User::findOrFail(1);
$model =User::where('votes','>',100)->firstOrFail();
註冊錯誤處理器,請監聽 ModelNotFoundException
useIlluminate\Database\Eloquent\ModelNotFoundException;
App::error(function(ModelNotFoundException $e)
{
returnResponse::make('Not Found',404);
});
指定查詢的資料庫連線
$user =User::on('connection-name')->find(1);
插入
$user =newUser;
$user->name ='John';
$user->save();
通常您的 Eloquent 模型將有自動遞增的鍵。然而,如果您希望指定您自定義的鍵,在模型中設定 incrementing 屬性為 false。
您也可以使用 create 函式在一行程式碼中儲存一個新的模型。被插入的模型例項將從函式中返回。但是,在您這樣做之前,您需要在模型中指定 fillable 或者 guarded 屬性,因為所有 Eloquent 模型預設阻止集體賦值。
$user =User::create(array('name'=>'John'));
更新
$user =User::find(1);
$user->email ='[email protected]';
$user->save();
有時您可能希望不僅儲存模型,還有它的所有關係。為此,您可以使用 push 函式:
$user->push();
在一組模型上執行更新:
$affectedRows =User::where('votes','>',100)->update(array('status'=>2));
刪除
$user =User::find(1);
$user->delete();
根據主鍵刪除一個模型
User::destroy(1);
User::destroy(1,2,3);
一組模型中執行刪除查詢
$affectedRows =User::where('votes','>',100)->delete();
如果您希望簡單的在一個模型中更新時間戳,可以使用 touch 函式
$user->touch();
軟刪除
並沒有真的從資料庫中刪除。相反,一個 deleted_at 時間戳在記錄中被設定。為一個模型開啟軟刪除,在模型中指定 softDelete 屬性
classUserextendsEloquent{
protected $softDelete =true;
}
在您的表中新增一個 deleted_at 欄位,您可以在遷移中使用 softDeletes 函式:
$table->softDeletes();
當您在一個模型中呼叫 delete 函式,deleted_at欄位將被設定為當前的時間戳。在使用軟刪除的模型中查詢,被軟刪除的模型將不被包含進查詢結果中。為了強制已刪除的模型出現在結果集中,在查詢中使用 withTrashed 函式:
$users =User::withTrashed()->where('account_id',1)->get();
希望在結果集中只包含軟刪除的模型,您可以使用 onlyTrashed 函式
$users =User::onlyTrashed()->where('account_id',1)->get();
恢復一個已被軟刪除的記錄,使用 restore 函式:
$user->restore();
在查詢中使用 restore 函式:
User::withTrashed()->where('account_id',1)->restore();
restore 函式也可以在關係中被使用:
$user->posts()->restore();
從資料庫中真正刪除一個模型,您可以使用 forceDelete 函式:
$user->forceDelete();
檢測一個給定的模型例項是否被軟刪除,可以使用 trashed 函式:
if($user->trashed())
{
//
}
查詢範圍
範圍允許您容易在模型中重用查詢邏輯。定義一個範圍,簡單的用 scope 為模型新增字首
classUserextendsEloquent{
publicfunction scopePopular($query)
{
return $query->where('votes','>',100);
}
}
使用一個查詢範圍
$users =User::popular()->orderBy('created_at')->get();
使用引數
classUserextendsEloquent{
publicfunction scopeOfType($query, $type)
{
return $query->whereType($type);
}
}
然後在範圍函式呼叫中傳遞引數:
$users =User::ofType('member')->get();