为什么我的detach()和delete()不起作用?

时间:2018-04-29 14:25:05

标签: php mysql laravel laravel-5

我正在使用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(Model)

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();处的评论,我的应用程序崩溃了。

1 个答案:

答案 0 :(得分:0)

也许你的模型不知道if (item.GetType().FullName.Equals("DataContract.Event")) { //Not sure if this is the right approach here but it works var serializedObject = JsonConvert.SerializeObject(item, Formatting.Indented); var deserializedObject = JsonConvert.DeserializeObject<DataContract.Event>(x); view.FindViewById<TextView>(Resource.Id.textView1).Text = deserializedObject.Name; view.FindViewById<TextView>(Resource.Id.textView2).Text = deserializedObject.EventDateTime.ToString(); } 的价值是什么?

我不建议在模型中使用开关。模型关系是引导顺序的一部分。您必须将其拆分为$this->typejournalDetailsconferenceDetails,然后在控制器中进行正确选择。

editorshipDetails