[扩展推荐] Laravel 模型关联事件
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 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: