Laravel 5.7 多对多 sync() 不起作用



>我有一个中间表,我想在其中保存sbj_type_iddifficulty_level_id所以我设置了这个:

$difficulty_level = DifficultyLevel::find(5);
if ($difficulty_level->sbj_types()->sync($request->hard, false)) {
    dd('ok');
}
else {
    dd('not ok');
}

这是我的难度级别.php:

public function sbj_types() {
     return $this->belongsToMany('AppSbjType');
}

这是我的SbjType.php:

public function difficulty_levels() {
    return $this->hasMany('AppDifficultyLevel');
}

在上面的代码中,我dd('ok')它返回正常,但数据库表为空。

尝试更改

return $this->hasMany('AppDifficultyLevel'); 

return $this->belongsToMany('AppDifficultyLevel');

sync() 方法采用一个数组,其中包含要同步的记录的 id,作为参数,您可以选择向其添加中间表值。虽然sync($request->hard, false)似乎没有在您的情况下抛出异常,但我看不出这将如何工作。

例如,尝试:

$difficulty_level->sbj_types()->sync([1,2,3]);

其中1,2,3sbj_types的 ID。

您可以在此处阅读有关同步的更多信息。

最新更新