【问题标题】:Dont insert value in pivot table (Laravel 5.8)不要在数据透视表中插入值(Laravel 5.8)
【发布时间】:2020-03-27 08:59:58
【问题描述】:

我有三个表学生,主题和数据透视表名称'student_subject',当使用附加(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');
    });
}                                

【问题讨论】:

    标签: php mysql pivot-table laravel-5.8


    【解决方案1】:

    如果您有多个复选框,则应将复选框名称设置为数组名称[]。

    Form::checkbox('name[]', $subject, false);

    然后你可以得到$request-&gt;name作为一个数组

    $subjects = $request->input('name');
    foreach($subjects as $subject){
     $student->subject()->attach($subject);
    }
    

    检查这个问题Laravel - Store multiple checkbox form values in database

    【讨论】:

    • 你能帮我看看任何办公桌或团队查看器吗
    猜你喜欢
    • 2014-08-24
    • 2020-09-19
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多