Php 如何在不使用Laravel中任何关系的情况下删除多表数据库中的数据

Php 如何在不使用Laravel中任何关系的情况下删除多表数据库中的数据,php,laravel,Php,Laravel,我的数据库中有2个表 首先是桌柱 Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->date('PostDate'); $table->string('PostTitle', 200); $table->string('GroupID', 100)->nullable();

我的数据库中有2个表

首先是桌柱

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->date('PostDate');
        $table->string('PostTitle', 200);
        $table->string('GroupID', 100)->nullable();
        $table->integer('LanguageID')->default(1);
        $table->timestamps();
    });
第二个是表后类别

Schema::create('post_categories', function (Blueprint $table) {
        $table->integer('post_id');
        $table->integer('category_id');
        $table->timestamps();
    });
每次我将post数据存储到数据库中时,它都将存储为两行。。因为我有两种活跃的语言。在我的post_categories表中,有category_id列。。因此,如果id=1的post数据有两个类别。。id=2的post数据有3个类别,它将在post_categories表中创建5行。 但是当我想删除帖子时,我会先从群组ID中进行检查。。因此,我也将删除2行。。 但问题是,我无法删除post_类别中的数据。。我正在使用foreach,但数据不会被删除

这是我的删除控制器:

public function destroy($id)
{
    $post = Post::findOrFail($id);
    Post::where('GroupID', $post->GroupID)->delete();
    $postGroups = Post::where('GroupID', $post->GroupID)->get();
    foreach ($postGroups as $postGroup) {
        DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
    }

    return response()->json([
        "error" => "0",
        "message" => "Success"
    ]);
}

我可以删除具有相同组ID的所有帖子,但不能删除具有相同帖子ID的帖子类别数据。

删除帖子之前先删除类别

public function destroy($id)
{
    $post = Post::findOrFail($id);

    $postGroups = Post::where('GroupID', $post->GroupID)->get();
    foreach ($postGroups as $postGroup) {
        DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
    }

    Post::where('GroupID', $post->GroupID)->delete();

    return response()->json([
        "error" => "0",
        "message" => "Success"
    ]);
}


为了获得更好的代码体验,我建议使用表结构,如
posts
posts\u categories
posts\u languages
。最后一个将包含有关多语言内容的数据,并与
帖子相关

在删除帖子之前删除类别

public function destroy($id)
{
    $post = Post::findOrFail($id);

    $postGroups = Post::where('GroupID', $post->GroupID)->get();
    foreach ($postGroups as $postGroup) {
        DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
    }

    Post::where('GroupID', $post->GroupID)->delete();

    return response()->json([
        "error" => "0",
        "message" => "Success"
    ]);
}


为了获得更好的代码体验,我建议使用表结构,如
posts
posts\u categories
posts\u languages
。最后一个将包含有关多语言内容的数据,并与
帖子相关

您已经选择了答案,但在您的情况下,最好使用
其中()


您已经选择了答案,但在您的情况下,最好使用
where()


这应该被接受为答案,也是最好的解决方案。哇,你说得对。。这是最好的解决办法。。谢谢你的反馈这应该被接受为答案,也是最好的解决方案。。这是最好的解决办法。。谢谢你的反馈