Laravel 观察者没有依附在枢轴上 table

Laravel observer not attaching on pivot table

我有一个 Category 模型,它与自身有父关系:

public function parent()
{
    return $this->belongsTo('App\Models\Category', 'parent_id', 'id');
}

FieldCategory

的多对多关系
public function fieldcategories()
{
    return $this->belongsToMany('App\Models\FieldCategory');
}

我有一个 CategoryObserver 来观察父项是否有任何变化(例如,如果一个类别被移动到子类别)是否有变化我想附加父项 FielCategory 条目到子类别

public function updated(Category $category)
{
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}
public function updateFieldCategories(Category $category)
{

    $category->fieldcategories()->detach();

    $parent = \App\Models\Category::find($category->parent->id);

    $parentFieldCategoriesArray = [];
    foreach ($parent->fieldcategories as $parentCat)
    {
        $parentFieldCategoriesArray[] = $parentCat->id;
    }
    $category->fieldcategories()->attach($parentFieldCategoriesArray);
}

它在 updated 上运行良好!但是当我尝试在 created 上做精确的事情时(当它选择了父级时)它失败了,我不知道为什么? 我已尝试调试此函数,并且 $parentFieldCategoriesArray 中填充了必要的 ID。看起来 $category->fieldcategories()->attach() 方法没有触发,我不知道为什么。 createdupdated 上的枢轴 table 中没有记录,它工作正常。 我正在使用 Laravel 5.6

有什么帮助吗?

更新: 根据要求,这是我创建的函数

public function created(Category $category)
{
    \Log::debug('PARENT: '.$category->parent_id);
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}

我在 1 年前问过这个问题。看到这个:

这里有 2 个选项。创建自定义 BelongsToMany 或创建自定义特征 BelongsToManySyncEvents

请参阅

只需添加:

public $afterCommit = true;

在观察者的开头class..它会等到交易完成,然后保存你的附加或分离..

请检查Laravel's documentation for that