問題描述
如果對記錄進行了更改,有沒有辦法使用 eloquent 模型更新 Laravel 中的記錄?我不希望任何用戶無緣無故地一遍又一遍地請求數據庫,只需點擊按鈕即可保存更改.我有一個 javascript
功能,可以根據頁面中的某些內容是否已更改啟用和禁用保存按鈕,但我想知道是否可以確保在服務器上執行此類功能邊也.我知道我可以自己完成它(意思是:不訴諸框架的內部功能)只是通過檢查記錄是否有變化,但在這樣做之前,我想知道 Laravel eloquent 模型是否已經處理好了這樣,我就不需要重新發明輪子了.
Is there any way to update a record in Laravel using eloquent models just if a change has been made to that record? I don't want any user requesting the database for no good reason over and over, just hitting the button to save changes. I have a javascript
function that enables and disables the save button according with whether something has changed in the page, but I would like to know if it's possible to make sure to do this kind of feature on the server side too. I know I can accomplish it by myself (meaning: without appealing to an internal functionality of the framework) just by checking if the record has change, but before doing it that way, I would like to know if Laravel eloquent model already takes care of that, so I don't need to re-invent the wheel.
這是我用來更新記錄的方式:
This is the way I use to update a record:
$product = Product::find($data["id"]);
$product->title = $data["title"];
$product->description = $data["description"];
$product->price = $data["price"];
//etc (string values were previously sanitized for xss attacks)
$product->save();
推薦答案
你已經做到了!
save()
將檢查模型中的某些內容是否已更改.如果沒有,它將不會運行數據庫查詢.
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
下面是IlluminateDatabaseEloquentModel@performUpdate
中相關部分的代碼:
Here's the relevant part of code in IlluminateDatabaseEloquentModel@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
<小時>
getDirty()
方法只是將當前屬性與創建模型時保存在 original
中的副本進行比較.這是在 syncOriginal()
方法中完成的:
The getDirty()
method simply compares the current attributes with a copy saved in original
when the model is created. This is done in the syncOriginal()
method:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
<小時>
如果你想檢查模型是否臟,只需調用 isDirty()
:
if($product->isDirty()){
// changes have been made
}
或者如果你想檢查某個屬性:
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
這篇關于Laravel Eloquent 更新僅在進行更改時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!