【发布时间】:2018-09-13 13:01:03
【问题描述】:
我无法弄清楚这个模型有什么问题,我似乎使用相同的方法通过使用相同的方法来更新“updated_by”字段。这是我的模型地址代码。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
class Address extends Model
{
//declare table since we not generate it using migrate laravel
protected $table = 'ADDRESS';
//assign all field as fillable
protected $guarded = [];
// Update field update_by for Address .
public static function boot()
{
//this function not work when updating
static::updating(function ($Address) {
$Address->created_by = Auth::user()->id;
});
//this function work perfectly
static::creating(function ($Address) {
$Address->updated_by = Auth::user()->id;
$Address->created_by = Auth::user()->id;
});
}
function getMember()
{
return $this->belongsTo('App\Mbrdata','mbr_id');
}
}
此代码在其他模型上完美运行,不知何故对于这个模型它不做任何事情。生病尝试跟踪错误,不知何故我不知道如何调试错误,因为我没有看到任何错误/异常消息。任何建议如何调试此类问题?因为我检查了我的日志,所以也没有记录任何错误。
更正:-
public static function boot()
{
//this function not work when updating
static::updating(function ($Address) {
$Address->updated_by = Auth::user()->id;
});
//this function work perfectly
static::creating(function ($Address) {
$Address->updated_by = Auth::user()->id;
$Address->created_by = Auth::user()->id;
});
}
但是在更正之后仍然相同,该字段仍然没有更新为当前用户。
【问题讨论】:
-
当通过 Eloquent 发布大规模更新时,已保存和更新的模型事件不会为更新的模型触发。这是因为在发布大规模更新时从未真正检索到模型。检查文档
-
这可能只是您的问题中的一个错字,但您的
updating()事件方法正在更新created_by字段,而不是updated_by字段。 -
对不起我的错字,实际上已经做了另一个,没关系,只是这个我不知道原因在哪里。
-
如何更新模型?顺便说一句:
boot()应始终以parent::boot();开头。