如何在laravel中将数据保存到数据透视表,我有两个表有多对多的关系,所以我创建数据透视表,我尝试插入myVar
方法,但它继续给我这个例外:
“message”:“在null上调用成员函数sync()”, “exception”:“Symfony \ Component \ Debug \ Exception \ FatalThrowableError”,
这是合约模型:
sync()
这里是RequiredSkills Model:
class Contract extends Model
{
public function skills(){
$this->belongsToMany(RequiredSkills::class , 'contract_skills')->withTimestamps();
}
}
}
这是控制器:
class RequiredSkills extends Model
{
public function contract(){
$this->belongsToMany(Contract::class , 'contract_skills');
}
如何解决异常?
答案 0 :(得分:0)
您不必将数据写入关系表laravel可以为您完成 使用“ sync()”功能时,Laraval会自动在“ contract_skills”表中记录该关系。
您没有将Contract写入数据库,因此没有ID,因此您将无法链接
合同和技能需要记录,然后才能致电
sync()函数将执行以下插入操作:
insert into [contract_skills] ([contract_id], [skill_id]) values (1, 1)
我将执行以下存储功能
class RequiredSkillsController extends Controller
{
public function store(Request $request){
//Create Contract in database
$contract = Contract::create($request->contract);
//Get skills id to link with contract
$data = $request->skills;
//syncs with additional data
$contract->skills()->sync(array_column($data, 'id'), ['user_id'=>auth()->guard('api')->user()->id]);
return $contract->refresh()->skills;
}
}