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

david001's avatar

How to query this with relationship

I have a query using join but i don't want to use join and want to get same result by using relationship

$result = User::where('id', 1)
            ->where('deleted', false)
          
            ->leftJoin('posts', 'posts.user_id', '=', 'users.id')
            ->groupBy(['users.id'])
            ->selectRaw('users.*, count(posts.id) as post_count')
            ->orderBy('users.id', 'DESC')
            ->first();
dd($result);

In User.php

  public function posts()
    {
        return $this->hasMany(\App\Post::class);
    }

and all posts belongs to user.

can you help me how to get same results without using join. Thanks

0 likes
3 replies
david001's avatar

sorry, updated. i have id in users table

Please or to participate in this conversation.