跟我一起學 Laravel-EloquentORM 基礎部分

mylxsw發表於2017-02-13

使用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_atupdated_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中,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物件的形式返回,引數為多個主鍵

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

查詢聚集函式結果

與查詢構造器查詢方法一樣,可以使用聚集函式返回結果,常見的比如maxminavgsumcount

$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_atupdated_at欄位設定時間戳,不需要手動指定

批量賦值插入

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

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

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

執行create操作就只有白名單或者黑名單之外的欄位可以更新了

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

除了create方法,還有兩外兩個方法可以使用firstOrNewfirstOrCreate

firstOrCreate方法用來使用給定的列值對查詢記錄,如果查不到則插入新的。fristOrNewfirstOrCreate類似,不同在於如果不存在,它會返回一個新的模型物件,不過該模型是未經過持久化的,需要手動呼叫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();

上述操作後,資料會被真實刪除。


參考:

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章