博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Laravel Relationship Events
阅读量:5149 次
发布时间:2019-06-13

本文共 2304 字,大约阅读时间需要 7 分钟。

Laravel Relationship Events is a package by Viacheslav Ostrovskiy that adds extra model relationship events. This package comes with the following traits that are used to register listeners on a model’s boot() method:

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

And from the above traits, here’s an example of a few events on a Country model that has many Users using the HasManyEventstrait:

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}."); }); } }

And the inverse of the relationship with this package might look like the following:

namespace App\Models;use Illuminate\Database\Eloquent\Model; use Chelout\RelationshipEvents\Concerns\HasBelongsToEvents; class User extends Model { use HasBelongsToEvents; /** * Get the country associated with the user. */ 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}."); }); } }

Using an overloaded associate() method, you can fire two events belongsToAssociating and belongsToAssociated:

$country = App\Models\Country::first();$user = factory(User::class)->create([    'name' => 'John Smith',]);// Assosiate user with country// This will fire belongsToAssociating and belongsToAssociated events$user->country()->associate($country);

Learn More

The package has  for each trait and association type. Check out the package on GitHub at .

 


Filed in:  

转载于:https://www.cnblogs.com/mouseleo/p/10424156.html

你可能感兴趣的文章
面试时被问到的问题
查看>>
注解小结
查看>>
list control控件的一些操作
查看>>
一月流水账
查看>>
判断字符串在字符串中
查看>>
Linux环境下Redis安装和常见问题的解决
查看>>
HashPump用法
查看>>
cuda基础
查看>>
Vue安装准备工作
查看>>
oracle 创建暂时表
查看>>
201421410014蒋佳奇
查看>>
Xcode5和ObjC新特性
查看>>
LibSVM for Python 使用
查看>>
Centos 7.0 安装Mono 3.4 和 Jexus 5.6
查看>>
CSS属性值currentColor
查看>>
java可重入锁reentrantlock
查看>>
浅谈卷积神经网络及matlab实现
查看>>
解决ajax请求cors跨域问题
查看>>
《收获,不止Oracle》pdf
查看>>
Real-Time Rendering 笔记
查看>>