Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dipcb05's avatar

Doesn't exist query

Hello, I have a problem with a query.

in posts table, i have posts.id, then, in reviews table, i have posts_id(foreign key -> posts.id), reviews.id. i want to query those posts_id which doesn't exist in reviews table(post_id).

i am trying like ->

$r = DB::table('reviews')
            ->select(DB::raw('count(id) as rev_count, posts_id'))
            ->groupBy('posts_id')
            ->get();
        foreach ($r as $rr)
        {
            $p = DB::table('posts')
                ->select('id')
                ->where('id', '!=', $rr->posts_id)
                ->get();
        }

seems, i have successfully extracted the correct value. but with too much complexity, maybe buggy. if any there direct query to extract it?

the tables setup->

reviews:

Schema::create('reviews', function (Blueprint $table)
        {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('posts_id');
            $table->unsignedBigInteger('users_id');
            $table->foreign('posts_id')
                  ->references('id')
                  ->on('posts');
....................

posts:

Schema::create('posts', function (Blueprint $table) {
            $table->id();
        ...................

TIA

0 likes
2 replies

Please or to participate in this conversation.