0

How can I convert the following SQL query into Laravel query builder?

select
    *
from
    users
where
    EXISTS (
    SELECT
        *
    from
        posts
    where
        posts.created_by = users.id )

2 Answers 2

2

The following should work:

DB::table('users')
    ->whereExists(function ($query) {
        $query->select('*')
            ->from('posts')
            ->whereRaw('posts.created_by = users.id');
    })
    ->get();

You can also take a look at the documentation.

Sign up to request clarification or add additional context in comments.

5 Comments

What do you mean? This will retrieve all users that have a record (or more) in posts.
Also as you can see from this example, it outputs the query you need :)
You are welcome. Please consider upvoting/marking it as the answer if it worked for you :)
Why use whereRaw instead of ->where('posts.created_by', '=', 'users.id') ?
Both would work. However whereRaw() can be slightly faster in this case.
1

You can use has method with the corresponding relationship.

To do this:

  1. Create User and Post models.
  2. Define the relationships between the models, e.g. User has many Post with posts as relationship and Post belongs to User.
  3. Use the relationship with has method like this: User::has('posts')->get() where posts is the name of the relationship in User model.

From docs:

When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has and orHas methods:

// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();

So in your code, it will retrieve all users that have at least one post

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.