我的项目任务和办公室表中有多对多关系: 任务模型:
public function offices(): BelongsToMany
{
return $this->belongsToMany(Office::class)->withPivot('main_office');
}
办公模式:
public function tasks(): BelongsToMany
{
return $this->belongsToMany(Task::class)->withPivot('main_office');
}
控制器中的存储功能:
public function store(taskRequestStore $request,TaskService $service)
{
$offices=Office::where([['top_office_id',null],['status',1]])->get();
$attributes = $request->all(['Caption','TaskDsc','TaskDate','Priority_id',
'Type','TaskFile','FilePath','StartDate','EndDate','Deadline',
'Commander_id','Status_id'
]);
$tasks = $service->create($attributes);
// dd($tasks,$offices);
$tasks->$offices->attach([1]);
return redirect()->back();
}
记录已插入到任务表中,但附加命令发出错误。
当活动 dd 时:
我的代码错误在哪里?
您的问题是这一行:
$tasks->$offices->attach([1]);
应该是:
$tasks->offices()->attach($offices);
因为您想要将办公室附加到任务,所以您必须调用关系(
offices()
而不是offices
)并传递您想要附加的内容。
如果使用
attach($offices)
不起作用,请使用 ->attach($offices->pluck('id')->toArray())
。
不过,您的问题是
$offices
为空,因此当您运行 ->get()
时您无法获取数据,因此它永远不会附加任何内容