>我正在尝试在模型上触发"已保存"事件。我以为我让它工作,在某种程度上是这样。我正在听 3 种不同的模型,它只适用于一种。下面代码中的"属性"模型。有什么理由为什么它只适用于一个以及为什么适用于那个?
<?php
namespace App'Providers;
use App'Clients'Attribute;
use App'Clients'Lead;
use App'Clients'Member;
use Illuminate'Support'ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Attribute::saved(function ($attribute) {
$meta = 'App'Clients'ClientMeta::firstOrCreate(['client_id' => $attribute->mem_id, 'meta_name' => 'profile_updated']);
$meta->meta_value = time();
$meta->save();
});
Lead::saved(function ($lead) {
if($lead->converted == 1)
{
$meta = 'App'Clients'ClientMeta::firstOrCreate(['client_id' => $lead->id, 'meta_name' => 'profile_updated']);
$meta->meta_value = time();
$meta->save();
}
});
Member::saved(function ($member) {
$meta = 'App'Clients'ClientMeta::firstOrCreate(['client_id' => $member->member_lead_trace, 'meta_name' => 'profile_updated']);
$meta->meta_value = time();
$meta->save();
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
所以像
use 'App'Clients'ClientMeta;
class Attribute extends Model
{
protected $fillable = [...];
protected static function boot()
{
parent::boot();
static::saved(function ($attribute) {
$meta = ClientMeta::firstOrCreate(['client_id' => $attribute->mem_id, 'meta_name' => 'profile_updated']);
$meta->meta_value = time();
$meta->save();
});
}
您需要
在方法名称中添加parent::boot()
和static
public static function boot()
{
parent::boot();
...
请确保根据 CRUD 方法使用正确的模型事件:
事件,根据拉拉维尔
雄辩的模型触发多个事件,允许您钩入各种事件 使用以下方法在模型生命周期中的点:创建, 创建, 更新, 更新, 保存, 保存, 删除, 删除, 恢复,恢复。事件允许您每次都轻松执行代码 在数据库中保存或更新特定的模型类。
例如,当您更新模型时,您可能希望执行以下操作:
public static function boot()
{
parent::boot();
static::updated(function ($attribute) { ... }
请注意,您还应该将其添加到每个模型,而不是应用程序提供程序。