我有3个模特
Event has many Shifts
Shift belongs to Event
Shift has many ShiftWorkers
ShiftWorker belongs to Shift
当我在控制器中使用此存储方法通过html表单一次保存所有模型时:
public function store(EventsForm $request)
{
//dd($request->all());
// save event
$event = Auth::user()->events()->create($request->all());
$total_shifts = count($request->shift_start);
$shifts = [];
for ($s = 0; $s <= $total_shifts-1; $s++ ) {
array_push($shifts, new Shift(['shift_start' => $request->shift_start[$s], 'shift_end' => $request->shift_end[$s]]));
}
// save shifts
$event->shifts()->saveMany($shifts);
$workers = [];
for ($w = 0; $w <= $total_shifts-1; $w++ ) {
array_push($workers, new ShiftWorker(['quantity' => $request->quantity[$w], 'hour_wage' => $request->hour_wage[$w]]));
}
// save workers
$event->shifts()->shift_workers()->saveMany($workers);
我收到此错误
调用未定义的方法Illuminate \ Database \ Query \ Builder :: shift_workers()
如何保存我的第三个模型(ShiftWorker)?
答案 0 :(得分:1)
每个班次都有hasMany
,因此您无法在集合上调用shift_workers()
。
你要循环,如下所示:
foreach ($event->shifts as $shift) {
$shift->shift_workers()->saveMany($workers);
}