問(wèn)題描述
如果對(duì)記錄進(jìn)行了更改,有沒(méi)有辦法使用 eloquent 模型更新 Laravel 中的記錄?我不希望任何用戶無(wú)緣無(wú)故地一遍又一遍地請(qǐng)求數(shù)據(jù)庫(kù),只需點(diǎn)擊按鈕即可保存更改.我有一個(gè) javascript
功能,可以根據(jù)頁(yè)面中的某些內(nèi)容是否已更改啟用和禁用保存按鈕,但我想知道是否可以確保在服務(wù)器上執(zhí)行此類功能邊也.我知道我可以自己完成它(意思是:不訴諸框架的內(nèi)部功能)只是通過(guò)檢查記錄是否有變化,但在這樣做之前,我想知道 Laravel eloquent 模型是否已經(jīng)處理好了這樣,我就不需要重新發(fā)明輪子了.
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.
這是我用來(lái)更新記錄的方式:
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();
推薦答案
你已經(jīng)做到了!
save()
將檢查模型中的某些內(nèi)容是否已更改.如果沒(méi)有,它將不會(huì)運(yùn)行數(shù)據(jù)庫(kù)查詢.
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
下面是IlluminateDatabaseEloquentModel@performUpdate
中相關(guān)部分的代碼:
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;
}
<小時(shí)>
getDirty()
方法只是將當(dāng)前屬性與創(chuàng)建模型時(shí)保存在 original
中的副本進(jìn)行比較.這是在 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;
}
<小時(shí)>
如果你想檢查模型是否臟,只需調(diào)用 isDirty()
:
if($product->isDirty()){
// changes have been made
}
或者如果你想檢查某個(gè)屬性:
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
這篇關(guān)于Laravel Eloquent 更新僅在進(jìn)行更改時(shí)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!