在Laravel中处理多对多关系时显示错误结果

时间:2018-11-07 17:17:10

标签: php laravel laravelcollective

在我的项目中,电影模型和演员模型之间有很多联系。当我尝试用数据库中的演员更新电影时,它会显示正确的结果,但是当我进入视图时,它将显示与数据库中不同的演员。这是我的代码:

edit.blade.php视图:

               <div class="col-md-6">
                    {!! Form::model($movie, ['method'=>'PATCH', 'action'=> ['MovieController@update', $movie->id]]) !!}
                <div class="form-group">
                    {!! Form::label('movie_name', 'Name:') !!}
                    {!! Form::text('movie_name', null, ['class'=> 'form-control'])!!}
                </div>
                <div class="form-group">
                    {!! Form::label('actor_name', 'Actors:') !!}
                    {!! Form::select('actor_name[]', $actors, null, ['class'=> 'form-control js-example-basic-multiple', 'multiple' => 'multiple'])!!}
                </div>
                <div class="form-group">
                    {!! Form::submit('Update Movie', ['class'=>'btn btn-primary col-md-6']) !!}
                </div>
                {!! Form::close() !!}
                {!! Form::open(['method'=>'DELETE', 'action'=> ['MovieController@destroy', $movie->id]]) !!}
                <div class="form-group">
                    {!! Form::submit('Delete Movie', ['class'=>'btn btn-danger col-md-6']) !!}
                </div>
                {!! Form::close() !!}
                </div>
                @section('scripts')
                   <script type="text/javascript">
                      $(document).ready(function() {
                        $('.js-example-basic-multiple').select2();
                        $('.js-example-basic-multiple').select2().val({!! json_encode($movie->actors()->allRelatedIds()) !!}).trigger('change');
 });
                   </script>
                @endsection

MovieController:

           public function edit($id)
           {
              $movie = Movie::findOrFail($id);
              $actors = Actor::pluck('actor_name');
              return view('movies.edit', compact('movie', 'actors'));
           }


           public function update(MovieRequest $request, $id)
           {
              DB::beginTransaction();
              try {
                    $movie = Movie::findOrFail($id);
                    $movie->update($request->all());
                    if (isset($request->actors)) {
                    $movie->actors()->sync($request->actors);
                    } else {
                    $movie->actors()->sync([]);
                    }
                    DB::commit();
                    } catch (\Exception $e) {
                    DB::rollBack();
                    }
                    Session::flash('success', 'A movie was successfully UPDATED in the database!');
                    return redirect()->route('movies.index', $movie->id);
                    }

0 个答案:

没有答案