[英]Dont insert value in pivot table (Laravel 5.8)
I have three table Students ,Subject and Pivot table name 'student_subject' ,when using attach(1) work it (Insert data in pivot table) .我有三个表 Students ,Subject 和 Pivot 表名称 'student_subject' ,当使用 attach(1) 工作时(在数据透视表中插入数据)。
but when using attach($request -> subject) dont work但是当使用 attach($request -> subject) 时不起作用
why ?为什么 ? i dont now
我不知道
Model :模型 :
class Student班级学生
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 :课程主题:
class Subject extends Model
{
protected $fillable = ['name','user_id'];
//
public function student()
{
return $this->belongsToMany(Student::class);
}
}
Student Controller学生管理员
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');
Create View :创建视图:
@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
Pivot table 'student_subject'数据透视表'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');
});
}
If you have multiple checkboxes you should set name of checkbox as an array name[].如果您有多个复选框,则应将复选框名称设置为数组名称[]。
Form::checkbox('name[]', $subject, false);
Then you can get $request->name
as an array然后你可以得到
$request->name
作为一个数组
$subjects = $request->input('name');
foreach($subjects as $subject){
$student->subject()->attach($subject);
}
Check this question Laravel - Store multiple checkbox form values in database检查这个问题Laravel - 在数据库中存储多个复选框表单值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.