我在用Laravel5,我想从数据库中删除一些数据
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>
网站.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.');
}
当我点击 Yes, Delete
按钮,它调用 destroy
中的方法 PublicationController
删除具有特定id的发布。我尝试注解所有代码,只保留 return redirect
查看是否调用了该方法,它是否有效。之后,我删除了对 detach()
函数,但在数据库中却莫名其妙地没有产生任何结果。最后,我删除了网站上的评论 $publication->details()->delete();
我的应用程序崩溃了。
1条答案
按热度按时间nimxete21#
也许你的模型不知道
$this->type
是?我不建议在模型中使用开关。模型关系是引导序列的一部分。你得把它分成几个部分
journalDetails
,conferenceDetails
以及editorshipDetails
在控制器中做出正确的选择。