我正在使用Laravel 5,正在尝试从数据库中删除一些数据

的HTML

<form method="post" action="{{route('publications.destroy', $publication->id)}}">
    {{csrf_field()}}
    {{method_field('DELETE')}}
    <button type="submit" class="btn btn-danger btn-sm" dusk="btn-confirmDeletePub">Yes, Delete</button>
</form>


web.php

Route::resource('publications','PublicationController');


Publication.php(模型)

public function users()
{
    return $this->belongsToMany('App\User', 'user_publication');
}

public function topics()
{
    return $this->belongsToMany('App\Topic', 'topic_publication');
}

public function authors()
{
    return $this->belongsToMany('App\Author', 'author_publication');
}

public function details()
{
        /*
        Since we must join the publications table with one of the
        journals/conference/editorship table (based on type column' value)
        to retrieve publication'details,  we "aggregate" the 3 alternatives in this method.

        this method is useful for retrieving from db,
        for insertions, the 3 methods above ( journal(),conference(),editorship())
        should be used
        */
        switch ($this->type) {
            case 'journal':
                return $this->hasOne('App\Journal');
                break;

            case 'conference':
                return $this->hasOne('App\Conference');
                break;

            case 'editorship':
                return $this->hasOne('App\Editorship');
                break;

        }
 }


PublicationController.php

public function destroy($id)
{
    $publication = Publication::find($id);
    $publication->users()->detach($publication->id);
    $publication->topics()->detach($publication->id);
    $publication->authors()->detach($publication->id);
    //dd($publication);
    $publication->details()->delete();

    //$publication->delete();

    //Redirect('/users')->with('success', 'Publication deleted correctly.');

    return redirect('/users')->with('success', 'Publication deleted correctly.');

}


当我单击HTML表单中的Yes, Delete按钮时,它将调用destroy中的PublicationController方法以删除具有特定ID的发布。我试图注释所有代码,只留下return redirect来查看该方法是否被调用,并且它有效。
之后,我删除了对detach()函数的注释,但是在数据库中莫名其妙地它们没有产生任何结果。最后,我在$publication->details()->delete();处删除了注释,我的应用程序崩溃了。

最佳答案

也许您的模型不知道$this->type的值是什么?

我不建议在模型中使用开关。模型关系是引导顺序的一部分。您必须将其分为journalDetailsconferenceDetailseditorshipDetails,然后在控制器中做出正确的选择。

public function journalDetails()
{
  return $this->hasOne('App\Journal');
}
public function conferenceDetails()
{
  return $this->hasOne('App\Conference');
}
public function editorshipDetails()
{
  return $this->hasOne('App\Editorship');
}

10-05 21:07
查看更多