歡迎大家關注我的其他<a >Github博客</a>和<a >CSDN</a>,互相交流!
今天學習了Laravel中的ORM基礎部分,現在分享一下。
Eloquent ['el?kw?nt]
時,數據庫查詢構造器的方法對模型類也是也用的,使用上只是省略了DB::table
('表名')部分。
在模型中使用protected成員變量$table指定綁定的表名。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_flights';
}
Eloquent
假設每個表都有一個名為id的主鍵,可以通過$primaryKey
成員變量覆蓋該字段名稱,另外,Eloquent
假設主鍵字段是自增的整數,如果你想用非自增的主鍵或者非數字的主鍵的話,必須指定模型中的public
屬性$incrementing
為false
。
默認情況下,Eloquent
期望表中存在created_at
和updated_at
兩個字段,字段類型為timestamp
,如果不希望這兩個字段的話,設置$timestamps
為false
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}
使用protected $connection = 'connection-name'指定模型采用的數據庫連接。
查詢#
基本查詢操作#
方法all用于返回模型表中所有的結果
$flights = Flight::all();
foreach ($flights as $flight) {
echo $flight->name;
}
也可以使用get
方法為查詢結果添加約束
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
可以看到,查詢構造器的方法對模型類也是可以使用的
在eloquent ORM中,get
和all
方法查詢出多個結果集,它們的返回值是一個Illuminate\Database\Eloquent\Collection
對象,該對象提供了多種對結果集操作的方法
public function find($key, $default = null);
public function contains($key, $value = null);
public function modelKeys();
public function diff($items)
...
該對象的方法有很多,這里只列出一小部分,更多方法參考API文檔 Collection 和使用說明文檔。對大量結果分段處理,同樣是使用chunk方法
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
//
}
});
查詢單個結果#
使用find
和first
方法查詢單個結果,返回的是單個的模型實例
// 通過主鍵查詢模型...
$flight = App\Flight::find(1);
// 使用約束...
$flight = App\Flight::where('active', 1)->first();
使用find
方法也可以返回多個結果,以Collection
對象的形式返回,參數為多個主鍵
$flights = App\Flight::find([1, 2, 3]);
如果查詢不到結果的話,可以使用findOrFail
或者firstOrFail
方法,這兩個方法在查詢不到結果的時候會拋出Illuminate\Database\Eloquent\ModelNotFoundException
異常
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
如果沒有捕獲這個異常的話,laravel會自動返回給用戶一個404的響應結果,因此如果希望找不到的時候返回404,是可以直接使用該方法返回的
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
查詢聚集函數結果#
與查詢構造器查詢方法一樣,可以使用聚集函數返回結果,常見的比如max, min,avg,sum,count等
$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');
分頁查詢#
分頁查詢可以直接使用paginate函數
LengthAwarePaginator paginate(
int $perPage = null,
array $columns = array('*'),
string $pageName = 'page',
int|null $page = null
)
參數說明
參數 類型 說明
perPage int 每頁顯示數量
columns array 查詢的列名
pageName string 頁碼參數名稱
page int 當前頁碼
返回值為 LengthAwarePaginator
對象。
$limit = 20;
$page = 1;
return Enterprise::paginate($limit, ['*'], 'page', $page);
插入#
基本插入操作#
插入新的數據只需要創建一個新的模型實例,然后設置模型屬性,最后調用save方法即可
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
在調用save方法的時候,會自動為created_at和updated_at字段設置時間戳,不需要手動指定
批量賦值插入#
使用create
方法可以執行批量為模型的屬性賦值的插入操作,該方法將會返回新插入的模型,在執行create
方法之前,需要先在模型中指定fillable
和guarded
屬性,用于防止不合法的屬性賦值(例如避免用戶傳入的is_admin
屬性被誤錄入數據表)。
指定$fillable
屬性的目的是該屬性指定的字段可以通過create
方法插入,其它的字段將被過濾掉,類似于白名單,而$guarded
則相反,類似于黑名單。
protected $fillable = ['name'];
// OR
protected $guarded = ['price'];
執行create操作就只有白名單或者黑名單之外的字段可以更新了
$flight = App\Flight::create(['name' => 'Flight 10']);
除了create方法,還有兩外兩個方法可以使用firstOrNew和firstOrCreate。
firstOrCreate
方法用來使用給定的列值對查詢記錄,如果查不到則插入新的。fristOrNew
與firstOrCreate
類似,不同在于如果不存在,它會返回一個新的模型對象,不過該模型是未經過持久化的,需要手動調用save方法持久化到數據庫。
// 使用屬性檢索flight,如果不存在則創建...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// 使用屬性檢索flight,如果不存在則創建一個模型實例...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
更新#
基本更新操作#
方法save不僅可以要用來插入新的數據,也可以用來更新數據,只需先使用模型方法查詢出要更新的數據,設置模型屬性為新的值,然后再save就可以更新了,updated_at字段會自動更新。
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
也可使用update方法對多個結果進行更新
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
刪除#
基本刪除操作#
使用delete
方法刪除模型
$flight = App\Flight::find(1);
$flight->delete();
上述方法需要先查詢出模型對象,然后再刪除,也可以直接使用主鍵刪除模型而不查詢,使用destroy方法
App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);
使用約束條件刪除,返回刪除的行數
$deletedRows = App\Flight::where('active', 0)->delete();
軟刪除#
軟刪除是在表中增加deleted_at字段,當刪除記錄的時候不會真實刪除記錄,而是設置該字段的時間戳,由Eloquent模型屏蔽已經設置該字段的數據。
要啟用軟刪除,可以在模型中引用Illuminate\Database\Eloquent\SoftDeletes這個Trait,并且在dates屬性中增加deleted_at字段。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}
要判斷一個模型是否被軟刪除了的話,可以使用trashed方法
if ($flight->trashed()) {
//
}
查詢軟刪除的模型#
包含軟刪除的模型#
如果模型被軟刪除了,普通查詢是不會查詢到該結果的,可以使用withTrashed方法強制返回軟刪除的結果
$flights = App\Flight::withTrashed()
->where('account_id', 1)
->get();
// 關聯操作中也可以使用
$flight->history()->withTrashed()->get();
只查詢軟刪除的模型#
$flights = App\Flight::onlyTrashed()
->where('airline_id', 1)
->get();
還原軟刪除的模型#
查詢到軟刪除的模型實例之后,調用restore方法還原
$flight->restore();
也可以在查詢中使用
App\Flight::withTrashed()
->where('airline_id', 1)
->restore();
// 關聯操作中也可以使用
$flight->history()->restore();
強制刪除(持久化刪除)#
// Force deleting a single model instance...
$flight->forceDelete();
// Force deleting all related models...
$flight->history()->forceDelete();
上述操作后,數據會被真實刪除。