繁体   English   中英

在Laravel应用中触发模型事件

[英]Firing model events in Laravel app

我正在尝试在模型上触发“保存”事件。 我以为我可以使用它,并且在某种程度上是可以的。 我正在听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方法使用的模型事件正确:

事件,根据Laravel

雄辩的模型会触发多个事件,使您可以使用以下方法来陷入模型生命周期中的各个点:创建,创建,更新,更新,保存,保存,删除,删除,还原,还原。 通过事件,您可以在每次在数据库中保存或更新特定模型类时轻松地执行代码。

例如,当您更新模型时,您可能想要执行以下操作:

public static function boot()
    {
        parent::boot();

        static::updated(function ($attribute) { ... }

请注意,您还应该将其添加到每个模型,而不是应用程序提供商。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM