【发布时间】:2020-02-28 15:52:44
【问题描述】:
我是 Laravel 的新手,我对一件事感到好奇。我有 3 个数据库表:帖子、cmets、回复。我想对每个进行简单的删除。但显然帖子有很多 cmets,而 cmets 有很多回复。整个事情就是关于这些回复。好像我联系不上他们。
我在表之间有正常的工作关系。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use App\Reply;
use App\Traffic;
use Image;
use Illuminate\Support\Facades\Storage;
class PostsController extends Controller
{
//few others things here...
public function destroy($id) //$id is an id of post
{
// Select Post and comments of post
$post = Post::find($id);
$comments = Comment::where('post_id', $id);
//remove image (working fine)
Storage::delete('public/img/' . $post->image);
// delete all replies of post comments <<< Here is the issue. Can I even do like this?
foreach ($comments as $comment) {
$post_comment_reply = Reply::where('comment_id', $comment->id);
$post_comment_reply->delete();
}
// delete post record (working fine)
$post->delete();
//delete comments of post (working fine)
$comments->delete();
// return to user profile (working fine)
return redirect('/home')->with('success', 'Post has been deleted');
}
【问题讨论】:
-
这在数据库级别应该是自动的