在Laravel中使用同步功能时无法删除数据

时间:2019-07-12 08:00:43

标签: php laravel eloquent laravel-5.8

我正在开发laravel应用程序。在laravel中,我试图从数据透视表中删除一行及其相关数据。在此应用程序中,我有三个表:

issues: id, title, description

categories: id, name

category_issues:(pivot table) id, issue_id, category_id

在laravel中,我试图从数据透视表中删除一行及其相关数据。我有这种关系: Issue.php

public function categories() {
return $this->belongsToMany('App\Category', 'category_issues');
}

Category.php

public function issues() {
return $this->belongsToMany('App\Issue', 'category_issues');
}

问题可以有很多类别。

用于显示类别部分的HTML代码:

<div class="form-group row">
                    <label for="category" class="col-md-4 col-form-label text-md-right">{{ __('Category :') }}</label>
                    <div class="form-check col-md-6">
                      @foreach ($categories as $category)

                        <input type="checkbox" name="category[]" id="{{ $category->id }}" value="{{ $category->id }}"
                        {{ in_array($category->id, $issue->categories->pluck('id')->toArray())  ? 'checked' : '' }}>

                        <label for="{{ $category->id }}"> {{ $category->name }} </label>
                      @endforeach
                    </div>
                  </div>

这是更新功能文件:

public function update(Issue $issue)
{
    request()->validate([
      'title'=> ['required', 'min:3'],
      'description'=> ['required', 'min:3'],
      'category' => ['required']
    ]);

    $issue->title = request('title');
    $issue->description = request('description');
    $issue->save();

    //Category_Issue Update
    $cats = request('category');
    $issue->categories()->sync($cats);

    return redirect('issues')->with('success', 'Issue has been updated');
}

这是删除功能文件:

  public function destroy(Issue $issue)
{
  $issue->categories()->delete();
  return redirect('issues')->with('danger', 'Issue deleted');
}

1 个答案:

答案 0 :(得分:0)

您必须使用detach()删除数据透视表数据,

 $issue->categories()->detach();

查看此文档https://laravel.com/docs/5.8/eloquent-relationships