1. 首页
  2. Laravel

Laravel关系事件

Laravel Relationship Events是Viacheslav Ostrovskiy的一个包,它添加了额外的模型关系事件。此软件包具有以下特性,用于在模型\”sboot()上注册侦听器方法:
– hasone事件,下面是一个Country模型上的几个事件的例子,其中有许多Users使用HasManyEvents特性: 1namespace AppModels; 2 3use AppUser; 4use CheloutRelationshipEventsConcernsHasManyEvents; 5use IlluminateDatabaseEloquentModel; 6 7class Country extends Model 8{ 9use HasManyEvents;1011protected>12\”name\”,13];1415public function users()16{17return $this->hasMany(User::class);18}1920public static function boot()21{22parent::boot();2324static::hasManySaving(function ($parent, $related) {25Log::info(\”Saving user\”s country {$parent->name}.\”);26});2728static::hasManySaved(function ($parent, $related) {29Log::info(\”User\”s country is now set to {$parent->name}.\”);30});31}32},与此包的关系的倒数可能如下所示: 1namespace AppModels; 2 3use IlluminateDatabaseEloquentModel; 4use CheloutRelationshipEventsConcernsHasBelongsToEvents; 5 6class User extends Model 7{ 8use HasBelongsToEvents; 910/**11* Get the country associated with the user.12*/13public function country()14{15return $this->belongsTo(Country::class);16}1718protected static function boot()19{20parent::boot();2122static::belongsToAssociating(function ($relation, $related, $parent) {23Log::info(\”Associating country {$parent->name} with user.\”);24});2526static::belongsToAssociated(function ($relation, $related, $parent) {27Log::info(\”User has been assosiated with country {$parent->name}.\”);28});29}30}使用重载associate()方法,您可以触发两个事件belongsToAssociating和belongsToAssociated:25]);67// Assosiate user with country8// This will fire belongsToAssociating and belongsToAssociated events9$user->country()->associate($country);了解更多信息程序包中有每个特征和关联类型的文档。在chelout/laravel relationship events上查看GitHub上的包。

Laravel关系事件 为WP2原创文章,链接:https://www.wp2.cn/laravel/laravel%e5%85%b3%e7%b3%bb%e4%ba%8b%e4%bb%b6/