有条件的分离在许多关系laravel

时间:2017-03-01 06:54:38

标签: php laravel laravel-5.3

我有2个模型Tour.php

public function includes()
{
    return $this->belongsToMany('App\Included');
}

Included.php

public function tours()
{
    return $this->belongsToMany('App\Tour');
}

如果includeds中有tour,并且在删除游览时,我正试图分离includeds

以下代码是我尝试过的:

    public function destroy($id)
{
    $tour = Tour::find($id);

    if ($test = $tour->includeds()->count() != null) {
        $tour->includeds()->detach();
    }
    if ($test = $tour->excludeds()->count() != null) {
        $tour->excludeds()->detach();
    }        
    $tour->delete();

    Session::flash('success', 'The tour is sucessfully deleted.');
    return redirect()->route('tours.index');
}

以上代码生成Call to undefined method Illuminate\Database\Query\Builder::includeds()错误。请指出我正在制作的错误。

1 个答案:

答案 0 :(得分:1)

小错字

尝试使用以下代码

 public function destroy($id)
  {
    $tour = Tour::find($id);

    if ($test = $tour->includes()->count() != null) {
        $tour->includes()->detach();
    }
    if ($test = $tour->excludeds()->count() != null) {
        $tour->excludeds()->detach();
    }        
    $tour->delete();

    Session::flash('success', 'The tour is successfully deleted.');
    return redirect()->route('tours.index');
}