Laravel观察者没有附在枢轴桌上

vio*_*667 5 laravel laravel-5.6

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

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

和ManyToMany的关系 FieldCategory

public function fieldcategories()
{
    return $this->belongsToMany('App\Models\FieldCategory');
}
Run Code Online (Sandbox Code Playgroud)

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常updated!但是,当我尝试做一些确切的事情created(当它选择了父母时)它失败了,我不明白为什么?我试着调试这个函数,$parentFieldCategoriesArray并填充必要的ID.看起来这个$category->fieldcategories()->attach()方法没有解雇,我不知道为什么.有没有记录在数据透视表createdupdated它工作正常.我正在使用Laravel 5.6

有什么帮助吗?

更新:根据要求,这是我创建的功能

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

Jam*_*mie 4

我1年前问过这个问题。请参阅:Laravel 数据透视表观察者

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

请看我的问题