让我给你看看我的代码,并放上注释,让你们更好的理解。
$homework = new Homework([ // I create Homework (And I indeed want to get the ID of the one that was just created).
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->save(); // I save it
$homeworkid = Homework::where('id', $id)->first(); // I try to retrieve it, but I'm not sure how to get it as I need to define `$id`.
$progress = newProgress([
'user_id' => auth()->user()->id,
'homework_id' => $homeworkid, // I need this for the relationship to work.
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homeworkid->progress
]);
$progress->save(); // I save the progress
正如你们所看到的,我正在尝试检索一个模型的ID Homework
但我不知道该如何定义 $id
以便获取它。
解决方案:
如果你在实例化和保存之间没有做任何事情,就没有必要实例化一个新的模型并保存它,你可以使用 create
方法来代替。
$homework = Homework::create([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->id; // get the id
保存创建模型后,你可以访问 id
就像你平时一样。
$homework->id
然后你可以做的是设置 关系 在你的模型之间,所以你可以在创建一个新的作业后,进行以下操作。
$homework->newProgress()->create([
'user_id' => auth()->user()->id,
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homework->progress
]);
这样一来,你就不用再通过作业了 id
当创建一个新的 newProgress
,laravel会自动为你传递。