![](/img/trans.png)
[英]inserting data into database laravel 5.6 relation belongstomany pivot table
[英]How to add pivot table when inserting data to database in Laravel 8
也許有人知道如何在每次插入咨詢表時自動在 Laravel 8 中插入 pivot 表?
我有Model咨詢n對n問題,
輔導表
問題表
心理咨詢 Model
問題Model
Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class', 'counselings')->findOrFail($request->id);
return response()->json($student);
}
public function store(Request $request)
{ dd($request->all());
$counseling = new Counseling();
$counseling->student_id = $request->student_id;
$counseling->user_id = Auth::user()->id;
$counseling->save();
if ($counseling->save()) {
$problem = new Problem();
$problem->id = $request->has('problem_id');
$problem->save();
}
}
您可以通過幾種不同的方式插入到 pivot 表中。 我建議您參考此處的文檔。
您可以使用 attach 方法通過在關系的中間表中插入一條記錄來將角色附加到用戶:
例子:
$problem->counselings()->attach($counseling->id);
您還可以使用 sync 方法來構造多對多關聯。 sync 方法接受一組 ID 以放置在中間表上。 任何不在給定數組中的 ID 都將從中間表中刪除。
例子:
$problem->counselings()->sync($counselingsToSync);
多對多關系還提供了一種切換方法,可以“切換”給定相關 model ID 的附件狀態。 如果給定的 ID 當前已附加,它將被分離。 同樣,如果它當前是分離的,它將被附加:
例子:
$problem->counselings()->toggle($counselingsToToggle);
我會將您的 store() 方法更改為如下所示:
public function store(Request $request)
{
$counseling = Counseling::create([
'student_id' => $request->student_id,
'user_id' => Auth::user()->id
]);
if($request->has('problem_id'){
$counseling->problems()->attach($request->problem_id);
//return something if problem id is in request
}
//return something if problem id is not there
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.