Laravel-EloquentORM 基礎

歡迎大家關注我的其他<a >Github博客</a>和<a >CSDN</a>,互相交流!
今天學習了Laravel中的ORM基礎部分,現(xiàn)在分享一下。

Eloquent ['el?kw?nt] 時,數(shù)據(jù)庫查詢構造器的方法對模型類也是也用的,使用上只是省略了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假設主鍵字段是自增的整數(shù),如果你想用非自增的主鍵或者非數(shù)字的主鍵的話,必須指定模型中的public屬性$incrementingfalse。
默認情況下,Eloquent期望表中存在created_atupdated_at兩個字段,字段類型為timestamp,如果不希望這兩個字段的話,設置$timestampsfalse

<?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'指定模型采用的數(shù)據(jù)庫連接。

查詢#

基本查詢操作#
方法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中,getall方法查詢出多個結果集,它們的返回值是一個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) {
        //
    }
});

查詢單個結果#

使用findfirst方法查詢單個結果,返回的是單個的模型實例

// 通過主鍵查詢模型...
$flight = App\Flight::find(1);

// 使用約束...
$flight = App\Flight::where('active', 1)->first();

使用find方法也可以返回多個結果,以Collection對象的形式返回,參數(shù)為多個主鍵

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

查詢聚集函數(shù)結果#

與查詢構造器查詢方法一樣,可以使用聚集函數(shù)返回結果,常見的比如max, min,avg,sum,count等

$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');

分頁查詢#

分頁查詢可以直接使用paginate函數(shù)

LengthAwarePaginator paginate( 
    int $perPage = null, 
    array $columns = array('*'), 
    string $pageName = 'page', 
    int|null $page = null
)

參數(shù)說明
參數(shù) 類型 說明
perPage int 每頁顯示數(shù)量
columns array 查詢的列名
pageName string 頁碼參數(shù)名稱
page int 當前頁碼

返回值為 LengthAwarePaginator 對象。

$limit = 20;
$page = 1;
return Enterprise::paginate($limit, ['*'], 'page', $page);

插入#

基本插入操作#

插入新的數(shù)據(jù)只需要創(chuàng)建一個新的模型實例,然后設置模型屬性,最后調用save方法即可

$flight = new Flight;
$flight->name = $request->name;
$flight->save();

在調用save方法的時候,會自動為created_at和updated_at字段設置時間戳,不需要手動指定

批量賦值插入#

使用create方法可以執(zhí)行批量為模型的屬性賦值的插入操作,該方法將會返回新插入的模型,在執(zhí)行create方法之前,需要先在模型中指定fillableguarded屬性,用于防止不合法的屬性賦值(例如避免用戶傳入的is_admin屬性被誤錄入數(shù)據(jù)表)。

指定$fillable屬性的目的是該屬性指定的字段可以通過create方法插入,其它的字段將被過濾掉,類似于白名單,而$guarded則相反,類似于黑名單。

protected $fillable = ['name'];
// OR
protected $guarded = ['price'];

執(zhí)行create操作就只有白名單或者黑名單之外的字段可以更新了

$flight = App\Flight::create(['name' => 'Flight 10']);

除了create方法,還有兩外兩個方法可以使用firstOrNew和firstOrCreate。

firstOrCreate方法用來使用給定的列值對查詢記錄,如果查不到則插入新的。fristOrNewfirstOrCreate類似,不同在于如果不存在,它會返回一個新的模型對象,不過該模型是未經(jīng)過持久化的,需要手動調用save方法持久化到數(shù)據(jù)庫。

// 使用屬性檢索flight,如果不存在則創(chuàng)建...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// 使用屬性檢索flight,如果不存在則創(chuàng)建一個模型實例...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

更新#

基本更新操作#

方法save不僅可以要用來插入新的數(shù)據(jù),也可以用來更新數(shù)據(jù),只需先使用模型方法查詢出要更新的數(shù)據(jù),設置模型屬性為新的值,然后再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);

使用約束條件刪除,返回刪除的行數(shù)

$deletedRows = App\Flight::where('active', 0)->delete();

軟刪除#

軟刪除是在表中增加deleted_at字段,當刪除記錄的時候不會真實刪除記錄,而是設置該字段的時間戳,由Eloquent模型屏蔽已經(jīng)設置該字段的數(shù)據(jù)。

要啟用軟刪除,可以在模型中引用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();

// 關聯(lián)操作中也可以使用
$flight->history()->withTrashed()->get();

只查詢軟刪除的模型#

$flights = App\Flight::onlyTrashed()
      ->where('airline_id', 1)
      ->get();

還原軟刪除的模型#

查詢到軟刪除的模型實例之后,調用restore方法還原

$flight->restore();

也可以在查詢中使用

App\Flight::withTrashed()
    ->where('airline_id', 1)
    ->restore();

// 關聯(lián)操作中也可以使用
$flight->history()->restore();

強制刪除(持久化刪除)#

// Force deleting a single model instance...
$flight->forceDelete();

// Force deleting all related models...
$flight->history()->forceDelete();

上述操作后,數(shù)據(jù)會被真實刪除。

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容