Reputation: 1766
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 )
Upvotes: 0
Views: 42
Reputation: 1011
You can use has
method with the corresponding relationship.
To do this:
User
and Post
models.User
has many Post
with posts
as relationship and Post
belongs to User
. 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
Upvotes: 1
Reputation: 8750
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.
Upvotes: 2