我建议使用has but relationship来访问所有列表中的所有用户书籍。因此,如果用户每个都有3个列表和3本书。我可以一次访问所有9本书。
这要归功于这个答案,所以SO - > https://stackoverflow.com/a/49386095/9277589
删除列表时,如何删除图书。目前列表已删除,但书籍没有删除。
这就是我在视图中访问图书的方式。 $user->WatchedBooks
我试过这个
public function destroy($id){
$user = Auth::user();
$Watchlist = Watchlists::where('id', $id)->first();
if($Watchlist->user_id == Auth::id()){
$Watchlist->delete();
return redirect('watchlist');
} else {
return redirect('watchlist');
}
if($user->WatchedBooks == $user){
return redirect('watchlist');
} else {
return redirect('watchlist');
}
}
}
答案 0 :(得分:0)
您可以在迁移中使用它来创建表格
Schema::create('table_name', function (Blueprint $table) {
$table->integer('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
.
.
.
});
答案 1 :(得分:0)
您可以使用监视列表迁移文件中的$content = ob_get_clean();
方法设置外键:
onDelete('cascade)
或者您可以使用查询构建器和$table->foreign('watched_book_id')->references('id')->on('watched_books')->onDelete('cascade');
方法以编程方式执行此操作,如下所示:
delete()
这不需要更改数据库,并允许您在没有附加function yourDeleteMehod() {
[..]
$watchlist()->watchedBooks()->delete();
$watchlist()->delete();
[..]
}
的情况下WatchedBooks
。