use*_*140 69 php laravel eloquent
有没有办法使用雄辩模型更新Laravel中的记录,只要对该记录进行了更改?我不希望任何用户一遍又一遍地请求数据库没有正当理由,只需按下按钮即可保存更改.我有一个javascript
功能,根据页面中是否有更改,启用和禁用保存按钮,但我想知道是否可以确保在服务器端执行此类功能.我知道我可以自己完成它(意思是:没有吸引框架的内部功能)只是通过检查记录是否有变化,但在这样做之前,我想知道Laravel雄辩的模型是否已经处理好了那,所以我不需要重新发明轮子.
这是我用来更新记录的方式:
$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();
Run Code Online (Sandbox Code Playgroud)
luk*_*ter 142
你已经在做了!
save()
将检查模型中的某些内容是否已更改.如果没有它将不会运行数据库查询.
以下是代码的相关部分Illuminate\Database\Eloquent\Model@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
该getDirty()
方法只是将当前属性与original
创建模型时保存的副本进行比较.这是通过以下syncOriginal()
方法完成的:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
Run Code Online (Sandbox Code Playgroud)
如果要检查模型是否脏,请调用isDirty()
:
if($product->isDirty()){
// changes have been made
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要检查某个属性:
if($product->isDirty('price')){
// price has changed
}
Run Code Online (Sandbox Code Playgroud)
Ahm*_*sef 10
我想添加此方法,如果您使用的是编辑表单,则可以使用此代码保存update(Request $request, $id)
函数中的更改:
$post = Post::find($id);
$post->fill($request->input())->save();
Run Code Online (Sandbox Code Playgroud)
请记住,您必须使用相同的列名称命名输入.该fill()
功能将为您完成所有工作:)
归档时间: |
|
查看次数: |
66465 次 |
最近记录: |