Php 如何合并->;isDirty()与laravel->;更新()
我想检查数据库中的某些列是否已更改 控制器中的更新代码如下所示:Php 如何合并->;isDirty()与laravel->;更新(),php,laravel,laravel-5.5,Php,Laravel,Laravel 5.5,我想检查数据库中的某些列是否已更改 控制器中的更新代码如下所示: $tCustomer = TCustomer::withTrashed()->findOrFail($id); $tCustomer->update(request()->all()); 如何将其与->isDirty()函数合并 我尝试在$tCustomer->update(request()->all())之后添加它但它总是返回false: $dirty = $tCustomer->getDirty(
$tCustomer = TCustomer::withTrashed()->findOrFail($id);
$tCustomer->update(request()->all());
如何将其与->isDirty()函数合并
我尝试在$tCustomer->update(request()->all())之后添加它代码>但它总是返回false:
$dirty = $tCustomer->getDirty('payment_method_id');
我必须在更新之前还是之后添加isDirty()?isDirty
返回一个bool,因此您可以将它与条件一起使用,以检查给定的模型属性是否已更改。例如:
// modify an attribute
$myModel->foo = 'some new value';
....
// do other stuff
...
// before the model has been saved
if ($myModel->isDirty()) {
// update model
$myModel->save();
}
因此,需要在更新(保存)模型之前进行检查
调用update
可以在一次调用中保存具有给定属性的模型,这样您就不会在该上下文中使用isDirty
。您必须使用,您可以在保存模型之前或保存模型之后使用雄辩的模型事件,您只需在t客户
模型中添加以下代码:
public static function boot(){
static::updated(function($tCustomer){
if($tCustomer->isDirty('field_name')){
//This code will run only after model save and field_name is updated, You can do whatever you want like triggering event etc.
}
}
static::updating(function($tCustomer){
if($tCustomer->isDirty('field_name')){
//This code will run only before saving model and field_name is updating, You can do whatever you want like triggering event etc.
}
}
您可以使用fill()
代替update()
,检查isDirty()
,然后save()
。通过这种方式,您可以利用质量可注入场
$myModel->fill($arrayLikeinUpdate);
if ($myModel->isDirty()) {
// do something
}
$myModel->save();
我遇到了这个问题,我认为这是我在Laravel遇到的最奇怪的事情。当我更新它时,它不起作用,并且isdirty()方法返回false。。但是,当使用填充时,它就起作用了。非常感谢。