Eloquent:開始使用
簡介
Laravel 包含 Eloquent,這是一個物件關聯對映器 (ORM),可讓您愉快地與資料庫互動。使用 Eloquent 時,每個資料庫表格都有一個對應的「模型」,用於與該表格互動。除了從資料庫表格擷取記錄外,Eloquent 模型還允許您從表格中插入、更新和刪除記錄。
在開始之前,請務必在應用程式的 config/database.php
設定檔中設定資料庫連線。如需有關設定資料庫的詳細資訊,請參閱 資料庫設定文件。
Laravel 新手訓練營
如果您是 Laravel 的新手,請隨時跳入 Laravel 新手訓練營。Laravel 新手訓練營將引導您使用 Eloquent 建構您的第一個 Laravel 應用程式。這是了解 Laravel 和 Eloquent 所提供一切的好方法。
產生模型類別
首先,讓我們建立一個 Eloquent 模型。模型通常位於 app\Models
目錄中,並擴充 Illuminate\Database\Eloquent\Model
類別。您可以使用 make:model
Artisan 命令 來產生新的模型
php artisan make:model Flight
如果您希望在產生模型時產生 資料庫遷移,您可以使用 --migration
或 -m
選項
php artisan make:model Flight --migration
您可以在產生模型時產生各種其他類型的類別,例如工廠、填充器、策略、控制器和表單請求。此外,這些選項可以組合在一起以一次建立多個類別
# Generate a model and a FlightFactory class...php artisan make:model Flight --factoryphp artisan make:model Flight -f # Generate a model and a FlightSeeder class...php artisan make:model Flight --seedphp artisan make:model Flight -s # Generate a model and a FlightController class...php artisan make:model Flight --controllerphp artisan make:model Flight -c # Generate a model, FlightController resource class, and form request classes...php artisan make:model Flight --controller --resource --requestsphp artisan make:model Flight -crR # Generate a model and a FlightPolicy class...php artisan make:model Flight --policy # Generate a model and a migration, factory, seeder, and controller...php artisan make:model Flight -mfsc # Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...php artisan make:model Flight --allphp artisan make:model Flight -a # Generate a pivot model...php artisan make:model Member --pivotphp artisan make:model Member -p
檢查模型
有時,僅僅瀏覽模型的程式碼,很難確定模型的所有可用屬性和關係。相反,請嘗試使用 model:show
Artisan 命令,它提供了模型所有屬性和關係的便捷概述
php artisan model:show Flight
Eloquent 模型慣例
make:model
命令產生的模型將放置在 app/Models
目錄中。讓我們檢視一個基本模型類別,並討論一些 Eloquent 的主要慣例
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ // ...}
資料表名稱
在瀏覽上面的範例後,您可能已經注意到我們沒有告訴 Eloquent 哪個資料庫表格對應於我們的 Flight
模型。依照慣例,除非明確指定另一個名稱,否則類別的「蛇形命名法」複數名稱將用作表格名稱。因此,在這種情況下,Eloquent 會假設 Flight
模型將記錄儲存在 flights
表格中,而 AirTrafficController
模型則會將記錄儲存在 air_traffic_controllers
表格中。
如果您的模型對應的資料庫表格不符合此慣例,您可以透過在模型上定義 table
屬性來手動指定模型的表格名稱
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The table associated with the model. * * @var string */ protected $table = 'my_flights';}
主鍵
Eloquent 也會假設每個模型對應的資料庫表格都有一個名為 id
的主鍵欄。如有必要,您可以在模型上定義受保護的 $primaryKey
屬性,以指定作為模型主鍵的不同欄
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The primary key associated with the table. * * @var string */ protected $primaryKey = 'flight_id';}
此外,Eloquent 假設主鍵是一個遞增的整數值,這表示 Eloquent 會自動將主鍵轉換為整數。如果您希望使用非遞增或非數值的主鍵,您必須在模型上定義一個設定為 false
的公開 $incrementing
屬性
<?php class Flight extends Model{ /** * Indicates if the model's ID is auto-incrementing. * * @var bool */ public $incrementing = false;}
如果模型的主鍵不是整數,您應該在模型上定義一個受保護的 $keyType
屬性。此屬性的值應為 string
<?php class Flight extends Model{ /** * The data type of the primary key ID. * * @var string */ protected $keyType = 'string';}
「複合」主鍵
Eloquent 要求每個模型都至少有一個唯一識別的「ID」,可作為其主鍵。「複合」主鍵不受 Eloquent 模型支援。但是,除了表格唯一識別的主鍵之外,您可以自由地將其他多欄、唯一索引新增到您的資料庫表格中。
UUID 和 ULID 鍵
您可以選擇使用 UUID 而不是使用自動遞增的整數作為 Eloquent 模型的主鍵。UUID 是通用唯一的字母數字識別碼,長度為 36 個字元。
如果您希望模型使用 UUID 鍵而不是自動遞增的整數鍵,您可以在模型上使用 Illuminate\Database\Eloquent\Concerns\HasUuids
特徵。當然,您應該確保模型具有 UUID 等效的主鍵欄
use Illuminate\Database\Eloquent\Concerns\HasUuids;use Illuminate\Database\Eloquent\Model; class Article extends Model{ use HasUuids; // ...} $article = Article::create(['title' => 'Traveling to Europe']); $article->id; // "8f8e8478-9035-4d23-b9a7-62f4d2612ce5"
預設情況下,HasUuids
特徵會為您的模型產生 「排序的」UUID。這些 UUID 對於索引的資料庫儲存更有效率,因為它們可以按字典順序排序。
您可以透過在模型上定義 newUniqueId
方法來覆寫給定模型的 UUID 產生過程。此外,您可以透過在模型上定義 uniqueIds
方法來指定應接收 UUID 的欄
use Ramsey\Uuid\Uuid; /** * Generate a new UUID for the model. */public function newUniqueId(): string{ return (string) Uuid::uuid4();} /** * Get the columns that should receive a unique identifier. * * @return array<int, string> */public function uniqueIds(): array{ return ['id', 'discount_code'];}
如果您願意,您可以選擇使用「ULID」而不是 UUID。ULID 與 UUID 類似;但是,它們的長度僅為 26 個字元。與排序的 UUID 一樣,ULID 可以按字典順序排序,以實現高效的資料庫索引。若要使用 ULID,您應該在模型上使用 Illuminate\Database\Eloquent\Concerns\HasUlids
特徵。您也應該確保模型具有 ULID 等效的主鍵欄
use Illuminate\Database\Eloquent\Concerns\HasUlids;use Illuminate\Database\Eloquent\Model; class Article extends Model{ use HasUlids; // ...} $article = Article::create(['title' => 'Traveling to Asia']); $article->id; // "01gd4d3tgrrfqeda94gdbtdk5c"
時間戳記
預設情況下,Eloquent 期望您的模型對應的資料庫表格中存在 created_at
和 updated_at
欄位。當模型被建立或更新時,Eloquent 會自動設定這些欄位的值。如果您不希望這些欄位由 Eloquent 自動管理,您應該在模型上定義一個 $timestamps
屬性,並將其值設定為 false
。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false;}
如果您需要自訂模型時間戳記的格式,請在您的模型上設定 $dateFormat
屬性。此屬性決定日期屬性在資料庫中的儲存方式,以及在將模型序列化為陣列或 JSON 時的格式。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The storage format of the model's date columns. * * @var string */ protected $dateFormat = 'U';}
如果您需要自訂用於儲存時間戳記的欄位名稱,您可以在模型上定義 CREATED_AT
和 UPDATED_AT
常數。
<?php class Flight extends Model{ const CREATED_AT = 'creation_date'; const UPDATED_AT = 'updated_date';}
如果您想在不修改模型的 updated_at
時間戳記的情況下執行模型操作,您可以在傳遞給 withoutTimestamps
方法的閉包中對模型進行操作。
Model::withoutTimestamps(fn () => $post->increment('reads'));
資料庫連線
預設情況下,所有 Eloquent 模型都會使用為您的應用程式設定的預設資料庫連線。如果您想指定在與特定模型互動時應使用的不同連線,您應該在模型上定義一個 $connection
屬性。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The database connection that should be used by the model. * * @var string */ protected $connection = 'mysql';}
預設屬性值
預設情況下,新建立的模型實例不包含任何屬性值。如果您想為模型的一些屬性定義預設值,您可以在模型上定義一個 $attributes
屬性。放置在 $attributes
陣列中的屬性值應以原始的「可儲存」格式存在,就像它們剛從資料庫讀取的一樣。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The model's default values for attributes. * * @var array */ protected $attributes = [ 'options' => '[]', 'delayed' => false, ];}
設定 Eloquent 嚴格模式
Laravel 提供了幾種方法,讓您可以針對各種情況配置 Eloquent 的行為和「嚴格性」。
首先,preventLazyLoading
方法接受一個可選的布林參數,指示是否應防止延遲載入。例如,您可能希望僅在非生產環境中停用延遲載入,以便您的生產環境即使在生產程式碼中意外出現延遲載入的關聯關係時也能繼續正常運作。通常,此方法應在應用程式的 AppServiceProvider
的 boot
方法中調用。
use Illuminate\Database\Eloquent\Model; /** * Bootstrap any application services. */public function boot(): void{ Model::preventLazyLoading(! $this->app->isProduction());}
此外,您可以在嘗試填入不可填入的屬性時,指示 Laravel 拋出例外,方法是調用 preventSilentlyDiscardingAttributes
方法。這可以幫助防止在嘗試設定尚未添加到模型 fillable
陣列中的屬性時,在本地開發期間發生意外錯誤。
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());
擷取模型
建立模型並其關聯的資料庫表格後,您就可以開始從資料庫中檢索資料了。您可以將每個 Eloquent 模型視為一個功能強大的查詢建構器,讓您可以流暢地查詢與該模型關聯的資料庫表格。模型的 all
方法將檢索與該模型關聯的資料庫表格中的所有記錄。
use App\Models\Flight; foreach (Flight::all() as $flight) { echo $flight->name;}
建立查詢
Eloquent 的 all
方法將返回模型表格中的所有結果。但是,由於每個 Eloquent 模型都充當一個查詢建構器,因此您可以在查詢中添加額外的約束,然後調用 get
方法來檢索結果。
$flights = Flight::where('active', 1) ->orderBy('name') ->take(10) ->get();
由於 Eloquent 模型是查詢建構器,因此您應該查看 Laravel 查詢建構器提供的所有方法。您可以在編寫 Eloquent 查詢時使用任何這些方法。
重新整理模型
如果您已經有一個從資料庫檢索的 Eloquent 模型實例,您可以使用 fresh
和 refresh
方法「重新整理」該模型。 fresh
方法將從資料庫重新檢索模型。現有的模型實例將不受影響。
$flight = Flight::where('number', 'FR 900')->first(); $freshFlight = $flight->fresh();
refresh
方法將使用來自資料庫的新資料重新水合現有的模型。此外,其所有已載入的關聯關係也將被重新整理。
$flight = Flight::where('number', 'FR 900')->first(); $flight->number = 'FR 456'; $flight->refresh(); $flight->number; // "FR 900"
集合
如我們所見,Eloquent 方法(如 all
和 get
)會從資料庫檢索多個記錄。但是,這些方法不會返回純 PHP 陣列。相反,會返回 Illuminate\Database\Eloquent\Collection
的實例。
Eloquent 的 Collection
類別繼承自 Laravel 的基礎 Illuminate\Support\Collection
類別,該類別提供了各種有用的方法,用於與資料集合互動。例如,reject
方法可用於根據調用閉包的結果從集合中刪除模型。
$flights = Flight::where('destination', 'Paris')->get(); $flights = $flights->reject(function (Flight $flight) { return $flight->cancelled;});
除了 Laravel 基礎集合類別提供的方法之外,Eloquent 集合類別還提供了一些額外的方法,這些方法專門用於與 Eloquent 模型集合互動。
由於 Laravel 的所有集合都實作了 PHP 的可迭代介面,因此您可以像處理陣列一樣循環遍歷集合。
foreach ($flights as $flight) { echo $flight->name;}
分塊結果
如果您嘗試透過 all
或 get
方法載入數萬個 Eloquent 記錄,您的應用程式可能會記憶體不足。您可以使用 chunk
方法來更有效地處理大量模型,而不是使用這些方法。
chunk
方法將檢索 Eloquent 模型的一個子集,將它們傳遞給閉包進行處理。由於一次只檢索當前區塊的 Eloquent 模型,因此在處理大量模型時,chunk
方法將顯著減少記憶體使用量。
use App\Models\Flight;use Illuminate\Database\Eloquent\Collection; Flight::chunk(200, function (Collection $flights) { foreach ($flights as $flight) { // ... }});
傳遞給 chunk
方法的第一個參數是您希望每個「區塊」接收的記錄數。傳遞作為第二個參數的閉包將針對從資料庫檢索的每個區塊調用。將執行資料庫查詢來檢索傳遞給閉包的每個記錄區塊。
如果您要根據在迭代結果時也會更新的欄位來篩選 chunk
方法的結果,則應使用 chunkById
方法。在這些情況下使用 chunk
方法可能會導致意外和不一致的結果。在內部,chunkById
方法將始終檢索 id
欄位大於前一個區塊中最後一個模型的模型。
Flight::where('departed', true) ->chunkById(200, function (Collection $flights) { $flights->each->update(['departed' => false]); }, column: 'id');
由於 chunkById
和 lazyById
方法會將它們自己的「where」條件添加到正在執行的查詢中,因此您通常應該在閉包中邏輯地分組您自己的條件。
Flight::where(function ($query) { $query->where('delayed', true)->orWhere('cancelled', true);})->chunkById(200, function (Collection $flights) { $flights->each->update([ 'departed' => false, 'cancelled' => true ]);}, column: 'id');
使用惰性集合分塊
lazy
方法的工作方式與chunk
方法類似,因為在幕後,它會分塊執行查詢。但是,lazy
方法不是像以前一樣直接將每個區塊傳遞到回呼中,而是返回一個扁平化的 Eloquent 模型LazyCollection
,讓您可以將結果視為單一串流進行互動。
use App\Models\Flight; foreach (Flight::lazy() as $flight) { // ...}
如果您要根據在迭代結果時也會更新的欄位來篩選 lazy
方法的結果,則應使用 lazyById
方法。在內部,lazyById
方法將始終檢索 id
欄位大於前一個區塊中最後一個模型的模型。
Flight::where('departed', true) ->lazyById(200, column: 'id') ->each->update(['departed' => false]);
您可以使用 lazyByIdDesc
方法根據 id
的降序來篩選結果。
游標
與 lazy
方法類似,cursor
方法可用於在迭代數萬個 Eloquent 模型記錄時顯著減少應用程式的記憶體消耗。
cursor
方法只會執行單一資料庫查詢;但是,個別的 Eloquent 模型將在實際迭代它們之前不會被水合。因此,在迭代游標時,一次只會在記憶體中保留一個 Eloquent 模型。
由於 cursor
方法一次只在記憶體中保留單個 Eloquent 模型,因此它無法延遲載入關聯關係。如果您需要延遲載入關聯關係,請考慮使用lazy
方法代替。
在內部,cursor
方法使用 PHP 產生器來實作此功能
use App\Models\Flight; foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) { // ...}
cursor
返回一個 Illuminate\Support\LazyCollection
實例。惰性集合允許您使用在典型 Laravel 集合上可用的許多集合方法,同時一次只載入一個模型到記憶體中。
use App\Models\User; $users = User::cursor()->filter(function (User $user) { return $user->id > 500;}); foreach ($users as $user) { echo $user->id;}
儘管 cursor
方法比常規查詢使用更少的記憶體(一次只在記憶體中保留單個 Eloquent 模型),但它最終仍然會耗盡記憶體。這是因為 PHP 的 PDO 驅動程式會在內部緩存所有原始查詢結果在其緩衝區中。如果您正在處理非常大量的 Eloquent 記錄,請考慮使用lazy
方法代替。
進階子查詢
子查詢選擇
Eloquent 還提供了進階的子查詢支援,讓您可以在單一查詢中從相關表格提取資訊。例如,讓我們想像一下,我們有一個航班 destinations
表格和一個到目的地的 flights
表格。 flights
表格包含一個 arrived_at
欄位,指示航班何時到達目的地。
使用查詢建構器的 select
和 addSelect
方法可用的子查詢功能,我們可以選擇所有的 destinations
以及最近到達該目的地的航班名稱,使用單一查詢即可。
use App\Models\Destination;use App\Models\Flight; return Destination::addSelect(['last_flight' => Flight::select('name') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1)])->get();
子查詢排序
此外,查詢建構器的 orderBy
函數支援子查詢。繼續使用我們的航班範例,我們可以利用此功能根據最後一班航班抵達目的地的時間對所有目的地進行排序。同樣,這可以在執行單一資料庫查詢時完成。
return Destination::orderByDesc( Flight::select('arrived_at') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1))->get();
擷取單一模型 / 聚合
除了檢索與給定查詢匹配的所有記錄之外,您也可以使用 find
、first
或 firstWhere
方法檢索單一記錄。這些方法不會返回模型集合,而是返回單個模型實例。
use App\Models\Flight; // Retrieve a model by its primary key...$flight = Flight::find(1); // Retrieve the first model matching the query constraints...$flight = Flight::where('active', 1)->first(); // Alternative to retrieving the first model matching the query constraints...$flight = Flight::firstWhere('active', 1);
有時您可能希望在未找到結果時執行其他操作。findOr
和 firstOr
方法將返回單個模型實例,或者,如果未找到結果,則執行給定的閉包。閉包返回的值將被視為該方法的結果。
$flight = Flight::findOr(1, function () { // ...}); $flight = Flight::where('legs', '>', 3)->firstOr(function () { // ...});
找不到例外
有時您可能希望在未找到模型時拋出例外。這在路由或控制器中尤其有用。findOrFail
和 firstOrFail
方法將檢索查詢的第一個結果;但是,如果找不到結果,將拋出 Illuminate\Database\Eloquent\ModelNotFoundException
。
$flight = Flight::findOrFail(1); $flight = Flight::where('legs', '>', 3)->firstOrFail();
如果未捕獲 ModelNotFoundException
,則會自動將 404 HTTP 回應傳回給客戶端。
use App\Models\Flight; Route::get('/api/flights/{id}', function (string $id) { return Flight::findOrFail($id);});
擷取或建立模型
firstOrCreate
方法會嘗試使用給定的欄位 / 值配對來定位資料庫記錄。如果資料庫中找不到該模型,則會插入一筆記錄,其屬性是將第一個陣列參數與可選的第二個陣列參數合併而成的。
與 firstOrCreate
類似,firstOrNew
方法會嘗試在資料庫中找到符合指定屬性的記錄。但是,如果找不到模型,則會返回一個新的模型實例。請注意,firstOrNew
返回的模型尚未持久化到資料庫中。您需要手動呼叫 save
方法來持久化它。
use App\Models\Flight; // Retrieve flight by name or create it if it doesn't exist...$flight = Flight::firstOrCreate([ 'name' => 'London to Paris']); // Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...$flight = Flight::firstOrCreate( ['name' => 'London to Paris'], ['delayed' => 1, 'arrival_time' => '11:30']); // Retrieve flight by name or instantiate a new Flight instance...$flight = Flight::firstOrNew([ 'name' => 'London to Paris']); // Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes...$flight = Flight::firstOrNew( ['name' => 'Tokyo to Sydney'], ['delayed' => 1, 'arrival_time' => '11:30']);
擷取聚合
當與 Eloquent 模型互動時,您也可以使用 Laravel 查詢建構器提供的 count
、sum
、max
和其他聚合方法。正如您可能預期的,這些方法會返回一個純量值,而不是 Eloquent 模型實例。
$count = Flight::where('active', 1)->count(); $max = Flight::where('active', 1)->max('price');
插入和更新模型
插入
當然,在使用 Eloquent 時,我們不僅需要從資料庫中檢索模型,還需要插入新的記錄。幸運的是,Eloquent 使其變得簡單。若要將新記錄插入資料庫,您應該實例化一個新的模型實例,並在模型上設定屬性。然後,呼叫模型實例上的 save
方法。
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Models\Flight;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class FlightController extends Controller{ /** * Store a new flight in the database. */ public function store(Request $request): RedirectResponse { // Validate the request... $flight = new Flight; $flight->name = $request->name; $flight->save(); return redirect('/flights'); }}
在此範例中,我們將傳入的 HTTP 請求中的 name
欄位指派給 App\Models\Flight
模型實例的 name
屬性。當我們呼叫 save
方法時,將會插入一筆記錄到資料庫中。當呼叫 save
方法時,模型的 created_at
和 updated_at
時間戳記將會自動設定,因此無需手動設定它們。
或者,您可以使用 create
方法,使用單個 PHP 語句「儲存」一個新的模型。插入的模型實例將由 create
方法返回給您。
use App\Models\Flight; $flight = Flight::create([ 'name' => 'London to Paris',]);
但是,在使用 create
方法之前,您需要在模型類別上指定 fillable
或 guarded
屬性。這些屬性是必要的,因為所有 Eloquent 模型預設都會受到大量指派漏洞的保護。若要深入瞭解大量指派,請參閱大量指派文件。
更新
save
方法也可以用於更新已存在於資料庫中的模型。若要更新模型,您應該檢索它並設定您想要更新的任何屬性。然後,您應該呼叫模型的 save
方法。同樣,updated_at
時間戳記將會自動更新,因此無需手動設定其值。
use App\Models\Flight; $flight = Flight::find(1); $flight->name = 'Paris to London'; $flight->save();
有時,您可能需要更新現有模型,如果沒有符合的模型存在,則建立一個新模型。與 firstOrCreate
方法類似,updateOrCreate
方法會持久化模型,因此無需手動呼叫 save
方法。
在下面的範例中,如果存在起飛地點為 Oakland
且目的地地點為 San Diego
的航班,則會更新其 price
和 discounted
欄位。如果不存在此類航班,則會建立一個新航班,其屬性是將第一個參數陣列與第二個參數陣列合併而成的。
$flight = Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99, 'discounted' => 1]);
大量更新
也可以對符合給定查詢的模型執行更新。在此範例中,所有 active
且目的地為 San Diego
的航班都將被標記為延遲。
Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]);
update
方法預期一個欄位和值配對的陣列,表示應更新的欄位。update
方法會返回受影響的列數。
當透過 Eloquent 發出大量更新時,更新模型的 saving
、saved
、updating
和 updated
模型事件將不會被觸發。這是因為在發出大量更新時,實際上永遠不會檢索模型。
檢查屬性變更
Eloquent 提供了 isDirty
、isClean
和 wasChanged
方法來檢查模型的內部狀態,並判斷其屬性自模型最初檢索以來發生了哪些變更。
isDirty
方法會判斷模型的任何屬性自模型檢索以來是否已變更。您可以將特定的屬性名稱或屬性陣列傳遞給 isDirty
方法,以判斷是否有任何屬性為「髒」的。isClean
方法會判斷自模型檢索以來,屬性是否保持未變更。此方法也接受可選的屬性參數。
use App\Models\User; $user = User::create([ 'first_name' => 'Taylor', 'last_name' => 'Otwell', 'title' => 'Developer',]); $user->title = 'Painter'; $user->isDirty(); // true$user->isDirty('title'); // true$user->isDirty('first_name'); // false$user->isDirty(['first_name', 'title']); // true $user->isClean(); // false$user->isClean('title'); // false$user->isClean('first_name'); // true$user->isClean(['first_name', 'title']); // false $user->save(); $user->isDirty(); // false$user->isClean(); // true
wasChanged
方法會判斷在目前請求週期中,模型上次儲存時是否有任何屬性發生變更。如果需要,您可以傳遞屬性名稱來查看是否變更了特定屬性。
$user = User::create([ 'first_name' => 'Taylor', 'last_name' => 'Otwell', 'title' => 'Developer',]); $user->title = 'Painter'; $user->save(); $user->wasChanged(); // true$user->wasChanged('title'); // true$user->wasChanged(['title', 'slug']); // true$user->wasChanged('first_name'); // false$user->wasChanged(['first_name', 'title']); // true
getOriginal
方法會返回一個陣列,其中包含模型的原始屬性,無論模型自檢索以來發生了任何變更。如果需要,您可以傳遞特定的屬性名稱來取得特定屬性的原始值。
$user = User::find(1); $user->name; // John $user->name = "Jack";$user->name; // Jack $user->getOriginal('name'); // John$user->getOriginal(); // Array of original attributes...
大量賦值
您可以使用 create
方法,使用單個 PHP 語句「儲存」一個新的模型。插入的模型實例將由該方法返回給您。
use App\Models\Flight; $flight = Flight::create([ 'name' => 'London to Paris',]);
但是,在使用 create
方法之前,您需要在模型類別上指定 fillable
或 guarded
屬性。這些屬性是必要的,因為所有 Eloquent 模型預設都會受到大量指派漏洞的保護。
當使用者傳遞意外的 HTTP 請求欄位,且該欄位變更了您未預期的資料庫中的欄位時,就會發生大量指派漏洞。例如,惡意使用者可能會透過 HTTP 請求傳送 is_admin
參數,然後將其傳遞給模型的 create
方法,允許使用者將自己提升為管理員。
因此,若要開始,您應該定義要進行大量指派的模型屬性。您可以使用模型上的 $fillable
屬性來執行此操作。例如,讓我們將 Flight
模型的 name
屬性設定為可大量指派。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = ['name'];}
指定哪些屬性可大量指派後,您可以使用 create
方法在資料庫中插入新記錄。create
方法會返回新建立的模型實例。
$flight = Flight::create(['name' => 'London to Paris']);
如果您已經有模型實例,您可以使用 fill
方法使用屬性陣列來填入它。
$flight->fill(['name' => 'Amsterdam to Frankfurt']);
大量指派和 JSON 欄位
當指派 JSON 欄位時,必須在模型的 $fillable
陣列中指定每個欄位可大量指派的索引鍵。為了安全起見,當使用 guarded
屬性時,Laravel 不支援更新巢狀 JSON 屬性。
/** * The attributes that are mass assignable. * * @var array<int, string> */protected $fillable = [ 'options->enabled',];
允許大量指派
如果您想要讓所有屬性都可大量指派,您可以將模型的 $guarded
屬性定義為空陣列。如果您選擇解除保護您的模型,您應該特別小心,務必始終手動製作傳遞給 Eloquent 的 fill
、create
和 update
方法的陣列。
/** * The attributes that aren't mass assignable. * * @var array<string>|bool */protected $guarded = [];
大量指派例外狀況
預設情況下,在執行大量指派操作時,未包含在 $fillable
陣列中的屬性會被靜默捨棄。在生產環境中,這是預期的行為;但是,在本地開發期間,可能會導致對模型變更未生效的原因感到困惑。
如果您希望,您可以指示 Laravel 在嘗試填入不可填入的屬性時擲回例外狀況,方法是呼叫 preventSilentlyDiscardingAttributes
方法。通常,此方法應在應用程式的 AppServiceProvider
類別的 boot
方法中呼叫。
use Illuminate\Database\Eloquent\Model; /** * Bootstrap any application services. */public function boot(): void{ Model::preventSilentlyDiscardingAttributes($this->app->isLocal());}
Upsert
Eloquent 的 upsert
方法可用於在單個原子操作中更新或建立記錄。該方法的第一個參數由要插入或更新的值組成,而第二個參數列出了唯一識別相關表格中記錄的欄位。該方法的第三個也是最後一個參數是一個欄位陣列,如果資料庫中已存在符合的記錄,則應更新這些欄位。如果模型上啟用了時間戳記,upsert
方法將自動設定 created_at
和 updated_at
時間戳記。
Flight::upsert([ ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99], ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]], uniqueBy: ['departure', 'destination'], update: ['price']);
除了 SQL Server 以外的所有資料庫都要求 upsert
方法的第二個參數中的欄位具有「主要」或「唯一」索引。此外,MariaDB 和 MySQL 資料庫驅動程式會忽略 upsert
方法的第二個參數,並始終使用表格的「主要」和「唯一」索引來偵測現有記錄。
刪除模型
若要刪除模型,您可以呼叫模型實例上的 delete
方法。
use App\Models\Flight; $flight = Flight::find(1); $flight->delete();
您可以呼叫 truncate
方法來刪除模型的所有相關資料庫記錄。truncate
操作也會重設模型相關表格上的任何自動遞增 ID。
Flight::truncate();
依主索引鍵刪除現有模型
在上面的範例中,我們是先從資料庫中檢索模型,然後才呼叫 delete
方法。但是,如果您知道模型的主索引鍵,您可以透過呼叫 destroy
方法來刪除模型,而無需明確地檢索它。除了接受單個主索引鍵之外,destroy
方法還會接受多個主索引鍵、主索引鍵陣列或主索引鍵的集合。
Flight::destroy(1); Flight::destroy(1, 2, 3); Flight::destroy([1, 2, 3]); Flight::destroy(collect([1, 2, 3]));
如果您正在使用軟刪除模型,您可以透過 forceDestroy
方法永久刪除模型。
Flight::forceDestroy(1);
destroy
方法會個別載入每個模型並呼叫 delete
方法,以便為每個模型正確分派 deleting
和 deleted
事件。
使用查詢刪除模型
當然,您可以建構 Eloquent 查詢來刪除符合查詢條件的所有模型。在此範例中,我們將刪除所有標記為非活動的航班。與大量更新類似,大量刪除不會為已刪除的模型分派模型事件。
$deleted = Flight::where('active', 0)->delete();
當透過 Eloquent 執行大量刪除陳述式時,將不會為已刪除的模型分派 deleting
和 deleted
模型事件。這是因為在執行刪除陳述式時,實際上永遠不會檢索模型。
軟刪除
除了實際從資料庫中移除記錄外,Eloquent 還可以「軟刪除」模型。當模型被軟刪除時,它們實際上不會從資料庫中移除。相反,會在模型上設定 deleted_at
屬性,指出模型被「刪除」的日期和時間。若要為模型啟用軟刪除,請將 Illuminate\Database\Eloquent\SoftDeletes
特性新增至模型中。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\SoftDeletes; class Flight extends Model{ use SoftDeletes;}
SoftDeletes
特性會自動將 deleted_at
屬性轉換為 DateTime
/ Carbon
實例。
您也應該將 deleted_at
欄位新增至資料庫表格。Laravel 綱要建構器包含建立此欄位的輔助方法。
use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; Schema::table('flights', function (Blueprint $table) { $table->softDeletes();}); Schema::table('flights', function (Blueprint $table) { $table->dropSoftDeletes();});
現在,當您在模型上呼叫 delete
方法時,deleted_at
欄位將設定為目前的日期和時間。但是,模型的資料庫記錄將保留在表格中。當查詢使用軟刪除的模型時,軟刪除的模型將自動從所有查詢結果中排除。
若要判斷給定的模型實例是否已被軟刪除,您可以使用 trashed
方法。
if ($flight->trashed()) { // ...}
還原軟刪除的模型
有時,您可能希望「取消刪除」軟刪除的模型。若要還原軟刪除的模型,您可以在模型實例上呼叫 restore
方法。restore
方法會將模型的 deleted_at
欄位設定為 null
。
$flight->restore();
您也可以在查詢中使用 restore
方法來還原多個模型。同樣,與其他「大量」操作類似,這不會為還原的模型分派任何模型事件。
Flight::withTrashed() ->where('airline_id', 1) ->restore();
restore
方法也可以在建立關聯查詢時使用。
$flight->history()->restore();
永久刪除模型
有時您可能需要真正地從資料庫中移除模型。您可以使用 forceDelete
方法,從資料庫表格中永久移除軟刪除的模型。
$flight->forceDelete();
您也可以在建立 Eloquent 關聯查詢時使用 forceDelete
方法。
$flight->history()->forceDelete();
查詢軟刪除的模型
包含軟刪除的模型
如上所述,軟刪除的模型會自動從查詢結果中排除。但是,您可以透過在查詢中呼叫 withTrashed
方法,強制將軟刪除的模型包含在查詢結果中。
use App\Models\Flight; $flights = Flight::withTrashed() ->where('account_id', 1) ->get();
withTrashed
方法也可以在建立關聯查詢時呼叫。
$flight->history()->withTrashed()->get();
僅檢索軟刪除的模型
onlyTrashed
方法會檢索僅軟刪除的模型。
$flights = Flight::onlyTrashed() ->where('airline_id', 1) ->get();
修剪模型
有時您可能想要定期刪除不再需要的模型。為達成此目的,您可以將 Illuminate\Database\Eloquent\Prunable
或 Illuminate\Database\Eloquent\MassPrunable
trait 加入到您想要定期修剪的模型中。將其中一個 trait 加入到模型後,請實作 prunable
方法,此方法會返回一個 Eloquent 查詢建構器,以解析不再需要的模型。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Prunable; class Flight extends Model{ use Prunable; /** * Get the prunable model query. */ public function prunable(): Builder { return static::where('created_at', '<=', now()->subMonth()); }}
當將模型標記為 Prunable
時,您也可以在模型上定義一個 pruning
方法。此方法會在模型被刪除之前呼叫。此方法可用於在模型從資料庫中永久移除之前,刪除任何與模型相關聯的其他資源,例如已儲存的檔案。
/** * Prepare the model for pruning. */protected function pruning(): void{ // ...}
設定可修剪的模型後,您應該在應用程式的 routes/console.php
檔案中排程 model:prune
Artisan 命令。您可以自由選擇此命令應執行的適當間隔。
use Illuminate\Support\Facades\Schedule; Schedule::command('model:prune')->daily();
在幕後,model:prune
命令會自動偵測應用程式的 app/Models
目錄中的 "Prunable" 模型。如果您的模型位於不同的位置,您可以使用 --model
選項指定模型類別名稱。
Schedule::command('model:prune', [ '--model' => [Address::class, Flight::class],])->daily();
如果您希望在修剪所有其他偵測到的模型時排除某些模型,可以使用 --except
選項。
Schedule::command('model:prune', [ '--except' => [Address::class, Flight::class],])->daily();
您可以使用 --pretend
選項執行 model:prune
命令來測試您的 prunable
查詢。在模擬執行時,model:prune
命令只會報告如果實際執行命令將會修剪多少筆記錄。
php artisan model:prune --pretend
如果軟刪除的模型符合可修剪的查詢條件,則會被永久刪除(forceDelete
)。
大量修剪
當模型標記為 Illuminate\Database\Eloquent\MassPrunable
trait 時,會使用大量刪除查詢從資料庫中刪除模型。因此,不會調用 pruning
方法,也不會發送 deleting
和 deleted
模型事件。這是因為模型在刪除之前實際上不會被檢索,因此修剪過程效率更高。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\MassPrunable; class Flight extends Model{ use MassPrunable; /** * Get the prunable model query. */ public function prunable(): Builder { return static::where('created_at', '<=', now()->subMonth()); }}
複製模型
您可以使用 replicate
方法建立現有模型實例的未儲存副本。當您有許多相同屬性的模型實例時,此方法特別有用。
use App\Models\Address; $shipping = Address::create([ 'type' => 'shipping', 'line_1' => '123 Example Street', 'city' => 'Victorville', 'state' => 'CA', 'postcode' => '90001',]); $billing = $shipping->replicate()->fill([ 'type' => 'billing']); $billing->save();
若要從複製到新模型的屬性中排除一個或多個屬性,您可以將陣列傳遞給 replicate
方法。
$flight = Flight::create([ 'destination' => 'LAX', 'origin' => 'LHR', 'last_flown' => '2020-03-04 11:00:00', 'last_pilot_id' => 747,]); $flight = $flight->replicate([ 'last_flown', 'last_pilot_id']);
查詢範圍
全域範圍
全域作用域可讓您將約束條件新增至給定模型的所有查詢。Laravel 自己的軟刪除功能利用全域作用域僅從資料庫中檢索「未刪除」的模型。編寫您自己的全域作用域可以提供一種方便且簡單的方式來確保給定模型的每個查詢都收到某些約束。
產生作用域
若要產生新的全域作用域,您可以調用 make:scope
Artisan 命令,該命令會將產生的作用域放置在應用程式的 app/Models/Scopes
目錄中。
php artisan make:scope AncientScope
編寫全域作用域
編寫全域作用域很簡單。首先,使用 make:scope
命令產生一個實作 Illuminate\Database\Eloquent\Scope
介面的類別。Scope
介面要求您實作一個方法:apply
。apply
方法可以視需要在查詢中新增 where
約束或其他類型的子句。
<?php namespace App\Models\Scopes; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Scope; class AncientScope implements Scope{ /** * Apply the scope to a given Eloquent query builder. */ public function apply(Builder $builder, Model $model): void { $builder->where('created_at', '<', now()->subYears(2000)); }}
如果您的全域作用域正在將欄位新增至查詢的 select 子句,您應該使用 addSelect
方法,而不是 select
。這將防止意外取代查詢現有的 select 子句。
套用全域作用域
若要將全域作用域指派給模型,您可以將 ScopedBy
屬性放置在模型上。
<?php namespace App\Models; use App\Models\Scopes\AncientScope;use Illuminate\Database\Eloquent\Attributes\ScopedBy; #[ScopedBy([AncientScope::class])]class User extends Model{ //}
或者,您可以透過覆寫模型的 booted
方法並調用模型的 addGlobalScope
方法來手動註冊全域作用域。addGlobalScope
方法會將您的作用域實例作為其唯一引數接受。
<?php namespace App\Models; use App\Models\Scopes\AncientScope;use Illuminate\Database\Eloquent\Model; class User extends Model{ /** * The "booted" method of the model. */ protected static function booted(): void { static::addGlobalScope(new AncientScope); }}
在上面的範例中將作用域加入到 App\Models\User
模型後,對 User::all()
方法的呼叫將執行以下 SQL 查詢。
select * from `users` where `created_at` < 0021-02-18 00:00:00
匿名全域作用域
Eloquent 也允許您使用閉包定義全域作用域,這對於不需要單獨類別的簡單作用域特別有用。當使用閉包定義全域作用域時,您應該將您自己選擇的作用域名稱作為 addGlobalScope
方法的第一個引數提供。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model; class User extends Model{ /** * The "booted" method of the model. */ protected static function booted(): void { static::addGlobalScope('ancient', function (Builder $builder) { $builder->where('created_at', '<', now()->subYears(2000)); }); }}
移除全域作用域
如果您想要移除給定查詢的全域作用域,可以使用 withoutGlobalScope
方法。此方法會將全域作用域的類別名稱作為其唯一引數接受。
User::withoutGlobalScope(AncientScope::class)->get();
或者,如果您使用閉包定義全域作用域,您應該傳遞您指派給全域作用域的字串名稱。
User::withoutGlobalScope('ancient')->get();
如果您想要移除數個甚至所有查詢的全域作用域,可以使用 withoutGlobalScopes
方法。
// Remove all of the global scopes...User::withoutGlobalScopes()->get(); // Remove some of the global scopes...User::withoutGlobalScopes([ FirstScope::class, SecondScope::class])->get();
本機範圍
本機作用域可讓您定義常見的查詢約束條件集,您可以在整個應用程式中輕鬆地重複使用。例如,您可能需要經常檢索所有被認為「熱門」的使用者。若要定義作用域,請在 Eloquent 模型方法加上 scope
前綴。
作用域應始終返回相同的查詢建構器實例或 void
。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model; class User extends Model{ /** * Scope a query to only include popular users. */ public function scopePopular(Builder $query): void { $query->where('votes', '>', 100); } /** * Scope a query to only include active users. */ public function scopeActive(Builder $query): void { $query->where('active', 1); }}
使用本機作用域
一旦定義了作用域,您可以在查詢模型時呼叫作用域方法。但是,您在呼叫方法時不應包含 scope
前綴。您甚至可以將對不同作用域的呼叫鏈接起來。
use App\Models\User; $users = User::popular()->active()->orderBy('created_at')->get();
透過 or
查詢運算子組合多個 Eloquent 模型作用域可能需要使用閉包才能實現正確的邏輯分組。
$users = User::popular()->orWhere(function (Builder $query) { $query->active();})->get();
但是,由於這可能很麻煩,Laravel 提供了一個「高階」orWhere
方法,可讓您流暢地將作用域鏈接在一起,而無需使用閉包。
$users = User::popular()->orWhere->active()->get();
動態作用域
有時您可能希望定義一個接受參數的作用域。若要開始使用,只需將您的其他參數新增至您作用域方法的方法簽名中。作用域參數應定義在 $query
參數之後。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model; class User extends Model{ /** * Scope a query to only include users of a given type. */ public function scopeOfType(Builder $query, string $type): void { $query->where('type', $type); }}
一旦將預期的引數新增至您作用域方法的方法簽名中,您就可以在呼叫作用域時傳遞引數。
$users = User::ofType('admin')->get();
比較模型
有時您可能需要判斷兩個模型是否「相同」。is
和 isNot
方法可用於快速驗證兩個模型是否具有相同的主鍵、表格和資料庫連線。
if ($post->is($anotherPost)) { // ...} if ($post->isNot($anotherPost)) { // ...}
在使用 belongsTo
、hasOne
、morphTo
和 morphOne
關聯時,也可以使用 is
和 isNot
方法。當您想要比較相關模型而無需發出查詢來檢索該模型時,此方法特別有用。
if ($post->author()->is($user)) { // ...}
事件
想要將您的 Eloquent 事件直接廣播到您的用戶端應用程式嗎?請查看 Laravel 的模型事件廣播。
Eloquent 模型會發送數個事件,讓您可以掛鉤到模型生命週期的以下時刻:retrieved
、creating
、created
、updating
、updated
、saving
、saved
、deleting
、deleted
、trashed
、forceDeleting
、forceDeleted
、restoring
、restored
和 replicating
。
當從資料庫中檢索現有模型時,會發送 retrieved
事件。當第一次儲存新模型時,會發送 creating
和 created
事件。當修改現有模型並呼叫 save
方法時,會發送 updating
/ updated
事件。當模型被建立或更新時,即使模型的屬性未變更,也會發送 saving
/ saved
事件。以 -ing
結尾的事件名稱會在將模型變更持續保存之前發送,而以 -ed
結尾的事件則會在模型變更持續保存之後發送。
若要開始監聽模型事件,請在您的 Eloquent 模型上定義 $dispatchesEvents
屬性。此屬性會將 Eloquent 模型生命週期的各個點對應到您自己的事件類別。每個模型事件類別都應期望透過其建構函式接收受影響模型的實例。
<?php namespace App\Models; use App\Events\UserDeleted;use App\Events\UserSaved;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable; class User extends Authenticatable{ use Notifiable; /** * The event map for the model. * * @var array<string, string> */ protected $dispatchesEvents = [ 'saved' => UserSaved::class, 'deleted' => UserDeleted::class, ];}
在定義和對應您的 Eloquent 事件之後,您可以使用事件監聽器來處理這些事件。
當透過 Eloquent 發出大量更新或刪除查詢時,將不會為受影響的模型發送 saved
、updated
、deleting
和 deleted
模型事件。這是因為在執行大量更新或刪除時,實際上不會檢索模型。
使用閉包
您可以註冊閉包,而不是使用自訂事件類別,這些閉包會在發送各種模型事件時執行。通常,您應該在模型的 booted
方法中註冊這些閉包。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model{ /** * The "booted" method of the model. */ protected static function booted(): void { static::created(function (User $user) { // ... }); }}
如果需要,您可以在註冊模型事件時使用可排隊的匿名事件監聽器。這將指示 Laravel 使用您應用程式的佇列在背景中執行模型事件監聽器。
use function Illuminate\Events\queueable; static::created(queueable(function (User $user) { // ...}));
觀察者
定義觀察者
如果您正在監聽給定模型的許多事件,可以使用觀察者將所有監聽器分組到一個類別中。觀察者類別具有反映您希望監聽的 Eloquent 事件的方法名稱。每個方法都會接收受影響的模型作為其唯一的引數。make:observer
Artisan 命令是建立新觀察者類別的最簡單方法。
php artisan make:observer UserObserver --model=User
此命令會將新的觀察者放置在您的 app/Observers
目錄中。如果此目錄不存在,Artisan 會為您建立它。您新的觀察者將如下所示。
<?php namespace App\Observers; use App\Models\User; class UserObserver{ /** * Handle the User "created" event. */ public function created(User $user): void { // ... } /** * Handle the User "updated" event. */ public function updated(User $user): void { // ... } /** * Handle the User "deleted" event. */ public function deleted(User $user): void { // ... } /** * Handle the User "restored" event. */ public function restored(User $user): void { // ... } /** * Handle the User "forceDeleted" event. */ public function forceDeleted(User $user): void { // ... }}
若要註冊觀察者,您可以將 ObservedBy
屬性放置在對應的模型上。
use App\Observers\UserObserver;use Illuminate\Database\Eloquent\Attributes\ObservedBy; #[ObservedBy([UserObserver::class])]class User extends Authenticatable{ //}
或者,您可以透過調用您想要觀察的模型上的 observe
方法來手動註冊觀察者。您可以在應用程式的 AppServiceProvider
類別的 boot
方法中註冊觀察者。
use App\Models\User;use App\Observers\UserObserver; /** * Bootstrap any application services. */public function boot(): void{ User::observe(UserObserver::class);}
觀察者可以監聽其他事件,例如 saving
和 retrieved
。這些事件在事件文件中說明。
觀察者和資料庫交易
當在資料庫交易中建立模型時,您可能想要指示觀察者僅在資料庫交易提交後才執行其事件處理常式。您可以透過在您的觀察者上實作 ShouldHandleEventsAfterCommit
介面來達成此目的。如果沒有進行中的資料庫交易,事件處理常式將立即執行。
<?php namespace App\Observers; use App\Models\User;use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit; class UserObserver implements ShouldHandleEventsAfterCommit{ /** * Handle the User "created" event. */ public function created(User $user): void { // ... }}
靜音事件
您可能偶爾需要暫時「靜音」模型觸發的所有事件。您可以使用 withoutEvents
方法達成此目的。withoutEvents
方法會將閉包作為其唯一的引數接受。在此閉包中執行的任何程式碼都不會發送模型事件,並且閉包傳回的任何值都將由 withoutEvents
方法傳回。
use App\Models\User; $user = User::withoutEvents(function () { User::findOrFail(1)->delete(); return User::find(2);});
在沒有事件的情況下儲存單一模型
有時您可能希望「儲存」給定模型而不發送任何事件。您可以使用 saveQuietly
方法達成此目的。
$user = User::findOrFail(1); $user->name = 'Victoria Faith'; $user->saveQuietly();
您也可以在不觸發任何事件的情況下「更新」、「刪除」、「軟刪除」、「還原」和「複製」給定的模型。
$user->deleteQuietly();$user->forceDeleteQuietly();$user->restoreQuietly();