Laravel观察者未附着在透视表上

Laravel观察者未附着在透视表上,laravel,laravel-5.6,Laravel,Laravel 5.6,我有一个类别模型,它本身有一个父关系: public function parent() { return $this->belongsTo('App\Models\Category', 'parent_id', 'id'); } 与FieldCategory public function fieldcategories() { return $this->belongsToMany('App\Models\FieldCategory'); } 我有一个Cate

我有一个
类别
模型,它本身有一个父关系:

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);
}
而且在
更新后的
上运行良好!但是,当我试图在创建的
上执行确切的操作时(当它选择了父对象时),它失败了,我不知道为什么?
我已尝试调试此函数,
$parentFieldCategoriesArray
中填充了必要的ID。看起来
$category->fieldcategories()->attach()
方法没有启动,我不知道为什么。 在
已创建的
已更新的
上,透视表中没有记录。透视表工作正常。 我用的是拉威尔5.6

需要帮忙吗

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

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

我一年前问过这个问题。请参见:

这里有两个选项。创建一个自定义的
BelongsToMany
或创建一个自定义的trait
BelongsToManySyncEvents


请看

是否确实已将父级正确分配给新创建的类别?另外,您可以向我们展示您为您的观察者创建的函数吗?我已经更新了问题,向您展示了我的
创建的
函数。是的,我确信家长被正确分配了。