laravel9 多态关联 使用 sync
更新时中间表没有触发事件
#posts
-id
-title
#videos
-id
-title
-url
#tags
-id
-name
#taggables
-tag_id
-taggable_id
-taggable_type
# Post Model
class Post extend Model
{
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable')->using(Taggable::class);
}
}
#Video Model
class Video extend Model
{
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable')->using(Taggable::class);
}
}
#Tag Model
class Tag extend Model
{
}
#Taggable Model
class Taggable extend MorphPivot
{
public function tag(): BelongsTo
{
return $this->belongsTo(Tag::class);
}
protected static function booted()
{
static::created(function(self $taggable) {
$taggable->tag?->increment('usage_count');
});
static::deleted(function (self $taggable) {
$taggable->tag?->decrement('usage_count');
});
}
}
重点:在定义多态关系时使用 ->using(Taggable::class)