{{csrf_field()}} {{method_field('DELETE')}} -6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:39:14 25 4
gpt4 key购买 nike

我正在使用 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 表单中的“是,删除”按钮时,它会调用 PublicationController 中的 destroy 方法来删​​除出版物具体id。我尝试注释所有代码并仅保留返回重定向以查看该方法是否被调用以及它是否有效。之后,我删除了对 detach() 函数的注释,但莫名其妙地在数据库中它们没有产生任何结果。最后,我删除了 $publication->details()->delete(); 处的注释,然后我的应用程序崩溃了。

最佳答案

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

我不建议在模型中使用开关。模型关系是启动序列的一部分。您必须将其分成 journalDetailsconferenceDetailseditorshipDetails 并在 Controller 中做出正确的选择。

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

关于php - 为什么我的 detach() 和 delete() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50087623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com