[英]Dont insert value in pivot table (Laravel 5.8)
我有三個表 Students ,Subject 和 Pivot 表名稱 'student_subject' ,當使用 attach(1) 工作時(在數據透視表中插入數據)。
但是當使用 attach($request -> subject) 時不起作用
為什么 ? 我不知道
模型 :
班級學生
class Student extends Model
{
protected $fillable=['user_id','FullName','age','address','father_ID','photo_id','class_id'];
public function subject(){
return $this->belongsToMany(Subject::class);
}
public function classes(){
return $this->belongsTo('App\classes','class_id');
}
public function user(){
return $this->belongsTo('App\User');
}
public function photo(){
return $this->belongsTo('App\photo');
}
//
}
課程主題:
class Subject extends Model
{
protected $fillable = ['name','user_id'];
//
public function student()
{
return $this->belongsToMany(Student::class);
}
}
學生管理員
public function store(Request $request)
{
$input =$request->all();
$user =Auth::user();
if ($file = $request->file('photo_id')){
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$photo = photo::create(['file'=>$name]);
$input['photo_id']=$photo->id;
}
$student = $user->student()->create($input);
// $student = $user->student()->create($input);
$request['student_id'] = $request->id;
$student->subject()->attach(1);
dd($student);
return redirect('admin/students');
創建視圖:
@foreach($subjects as $subject)
<tr>
<td>
<div class="form-group" {{}}>
{!! Form::label('name', $subject) !!}
{!! Form::checkbox('name',$subject,false, ['class'=>'form-control'])!!}
</div>
</td>
</tr>
@endforeach
數據透視表'student_subject'
public function up()
{
Schema::create('student_subject', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('student_id');
$table->unsignedBigInteger('subject_id');
// $table->foreign('student_id')->references('id')->on('students');
$table->foreign('student_id')->references('id')->on('students');
$table->foreign('subject_id')->references('id')->on('subjects');
});
}
如果您有多個復選框,則應將復選框名稱設置為數組名稱[]。
Form::checkbox('name[]', $subject, false);
然后你可以得到$request->name
作為一個數組
$subjects = $request->input('name');
foreach($subjects as $subject){
$student->subject()->attach($subject);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.