[扩展推荐] Laravel 模型关联事件

file

Laravel Relationship Events 是 Viacheslav Ostrovskiy 开发的一个添加额外的模型关系事件的包。这个包带有以下特性用于在模型的 boot() 方法中注册事件监听器:

  • HasOneEvents
  • HasBelongsToEvents
  • HasManyEvents
  • HasBelongsToManyEvents
  • HasMorphOneEvents
  • HasMorphToEvents
  • HasMorphManyEvents
  • HasMorphToManyEvents
  • HasMorphedByManyEvents

基于以上特性,这里有一个 Country 模型上一些事件的例子,它有许多的 Users ,并使用了 HasManyEvents 特性:

namespace App\Models;

use App\User;
use Chelout\RelationshipEvents\Concerns\HasManyEvents;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasManyEvents;

    protected $fillable = [
        'name',
    ];

    public function users()
    {
        return $this->hasMany(User::class);
    }

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

        static::hasManySaving(function ($parent, $related) {
            Log::info("Saving user's country {$parent->name}.");
        });

        static::hasManySaved(function ($parent, $related) {
            Log::info("User's country is now set to {$parent->name}.");
        });
    }
}

与之相对应的使用该包的关联关系可能像如下所示:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Chelout\RelationshipEvents\Concerns\HasBelongsToEvents;

class User extends Model
{
    use HasBelongsToEvents;

    /**
     * 获取与用户关联的国家或地区
     */
    public function country()
    {
        return $this->belongsTo(Country::class);
    }

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

        static::belongsToAssociating(function ($relation, $related, $parent) {
            Log::info("Associating country {$parent->name} with user.");
        });

        static::belongsToAssociated(function ($relation, $related, $parent) {
            Log::info("User has been assosiated with country {$parent->name}.");
        });
    }
}

使用重载 associate() 方法,你可以触发 belongsToAssociating 和 belongsToAssociated 事件:

$country = App\Models\Country::first();

$user = factory(User::class)->create([
    'name' => 'John Smith',
]);

// 将用户与国家关联
// 这将触发 belongsToAssociating 和 belongsToAssociated 事件
$user->country()->associate($country);

了解更多

该包为每个特性和关联类型提供了 文档 。可以在 GitHub 上查看 chelout/laravel-relationship-events

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://laravel-news.com/relationship-ev...

译文地址:https://learnku.com/laravel/t/15243/exte...

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!