How to turn this SQL into a Laravel Query Builder query? - mysql

I have the following query in SQL that works perfectly but I can't get it to work in Laravel's query builder. Here is the SQL:
SQL
select count(listings_queue.mls_listing_id) from listings_queue
INNER JOIN listings
ON `listings_queue`.`mls_listing_id` = `listings`.`mls_listing_id`
WHERE `listings`.`mls_id`=`listings_queue`.`mls_id`
AND `listings`.`city`=`listings_queue`.`city`
Laravel Query Builder
$count = DB::table('listings_queue')
->join('listings', function($join)
{
$join->on('listings_queue.mls_listing_id', '=', 'listings.mls_listing_id');
})
->where('listings.mls_id','=','listings_queue.mls_id')
->where('listings.city', '=', 'listings_queue.city')
->count();
This produces a count of 0 yet the SQL above produces 11,550 rows.
If I do the Laravel Query Builder and use the toSql(); at the end, I get:
toSql(); in Laravel
select * from `listings_queue`
inner join `listings`
on `listings_queue`.`mls_listing_id` = `listings`.`mls_listing_id`
where `listings`.`mls_id` = ?
and `listings`.`city` = ?
The crazy thing here is that the raw SQL output looks the same other than the ? bindings. Coudl that be the problem? I don't understand why my query builder query running on the same database as the raw SQL at the top produces different results.
One other clue is that if I remove the where clause in my laravel query builder query, I get results.
I asked this question elsewhere but didn't do a good job explaining so here it is. Thanks so much for any help you can provide!

Remove the Closure like:
$count = DB::table('listings_queue')
->join('listings', 'listings_queue.mls_listing_id', '=', 'listings.mls_listing_id')
->where('listings.mls_id','=','listings_queue.mls_id')
->where('listings.city', '=', 'listings_queue.city')
->count();

Try this multiple condition of join
$count = \DB::table('listings_queue')
->select('listings_queue.*')
->distinct()
->join('listings', function ($join)
{
$join->on('listings_queue.mls_listing_id', '=', 'listings.mls_listing_id')
->on('listings_queue.mls_id', '=', 'listings.mls_id')
->on('listings_queue.city', '=', 'listings.city');
})
->count();

Related

Laravel DB query builder left join with related counts

I am new in Laravel and facing an issue with the DB query builder.
I want to fetch all the records from users table and want to count related wishlists in wishlists table. Here is my query.
select `users`.*, count(wishlists.id) as wishlists_count from `users` left join `wishlists` on `users`.`id` = `wishlists`.`uid` where `users`.`status` = 1 group by `wishlists`.`id`
I want to do it with laravel query builder. Here is what I am trying.
$leads = DB::table('users')
->selectRaw('users.*', 'count(wishlists.id) as wishlists_count')
->leftJoin('wishlists', 'users.id', '=', 'wishlists.uid')
->where('users.status',1)
->groupBy('wishlists.id')
->get();
It is showing this error.
Argument 2 passed to Illuminate\Database\Query\Builder::selectRaw()
must be of the type array, string given.
Any help will be greatly appreciated.
Thanks in Advance.
This should work. From the documentation, the second argument to selectRaw() is an optional array of bindings.
However, you can achieve what you are looking for with a combination of select() and DB::raw()
$leads = DB::table('users')
->select('users.*', DB::raw('count(wishlists.id) as wishlists_count'))
->leftJoin('wishlists', 'users.id', '=', 'wishlists.uid')
->where('users.status',1)
->groupBy('wishlists.uid')
->get();
Edit: The above answer is wrong. I would consider the following alternatives instead.
Either you could achieve it with a Sub-Query with something like the following:
$wishlist = Wishlist::select(DB::raw('count(wishlists.id)'))
->whereColumn('uid', 'users.id')
->getQuery();
$users = User::select('users.*')
->selectSub($wishlist, 'wishlists_count')
->get();
Or with a much easier way (assuming you have a wishlists relationship set up)
Users::withCount('wishlists')->get();
foreach($users as $user) {
echo $user->wishlists_count;
}

Laravel Query builder query equivalent to SQL query?

My query is working fine only problem in this where clause. Please tell me what will query builder query in Laravel, equivalent to this query
WHERE (interest_request.sender_id = 6 or interest_request.to_user_id = 6)
AND interest_request.interest_status =2
and profiles.profile_id not in (6)
I am using following query builder but not working
where('to_user_id',$my_profile_id)->orwhere
('sender_id',$my_profile_id)->where('interest_status','2')
->whereNotIn('profiles.profile_id', $my_profile_id)
In your particular case, you'll have to use a nested where clause:
->where(function ($query) use ($my_profile_id) {
$query->where('to_user_id', $my_profile_id)
->orWhere('sender_id', $my_profile_id);
})
->where('interest_status', 2)
->where('profile_id', '!=', $my_profile_id)
Also you don't need to use a whereIn (or whereNotIn) query if you have only one id in the list.
i would assume it will be the following in sql:
WHERE to_user_id = $my_profile_id
OR sender_id = $my_profile_id
AND interest_status = 2
AND profiles.profile_id NOT IN ($my_profile_id)
When i use orwhere() statements i use callback functions:
where(function($query) {$query->something})
->orwhere(function($query) {$query->otherOptions})

Need help on select statement to be used in laravel

select distinct clientID from Client where clientID not in (select clientID from courseDetails inner join course on coursedetails.courseID = course.courseID where coursedetails.courseID = '$courseID')
If your query is a complex one then you can use RAW query in laravel like:
$data = DB::select(DB::raw('your query'));
Reference
Note: DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.
I give you a starting point:
$results = DB::table('Client')
->whereNotIn('clientID', function($query) use ($courseID) {
$query->select('clientID')
->from('courseDetails')
->join('course', 'courseDetails.courseID', '=', 'course.courseID')
->where('coursedetails.courseID', '=', $courseID);
})->get();
This should get you going. You can tweak it as you want to get your expected result.
Adding to #Mayank answer, you can run raw SQL and pass parameter like this
$result = DB::select('select distinct... where coursedetails.courseID = ? ', [$courseID]);

Laravel query help needed

I have a question about Laravel queries, so I have a upload Model and database table which stores all my images. Then there is an Activity Model and database table which stores all my activities. For each activity I want a image.
So my Activity model has a 'uploads_id' column. I wrote the query like this:
$activity_images = DB::table('uploads')
->join('activities', 'uploads.id', '=', 'activities.upload_id')
->where('uploads.id', '=', 'activities.upload_id')
->get();
It cannot find the right image what am I doing wrong?
You are "joining" twice in your join and where clause. You connect uploads.id and activities.upload_id one time in the join and again in the where clause.
If you want to query for a special upload.id, your query should look like this:
$activity_images = DB::table('uploads')
->join('activities', 'uploads.id', '=', 'activities.upload_id')
->where('uploads.id', '=', '<yourUploadID>')
->get();
If you want all images, you can delete the where statement.
$activity_images = DB::table('uploads')
->join('activities', 'uploads.id', '=', 'activities.upload_id')
->get();
If you use join an inner join will be used.
You could also use leftJoin if you want all entries from the table uploads.
$activity_images = DB::table('uploads')
->leftJoin('activities', 'uploads.id', '=', 'activities.upload_id')
->get();
Does it solve your issue?

How to select count with Laravel's fluent query builder?

Here is my query using fluent query builder.
$query = DB::table('category_issue')
->select('issues.*')
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by(DB::raw('COUNT(issue_subscriptions.issue_id)'), 'desc')
->get();
As you can see, I am ordering by a count from the joined table. This is working fine. However, I want this count returned with my selections.
Here is the my raw sequel query that works fine.
Select issues.*, COUNT(issue_subscriptions.issue_id) AS followers
FROM category_issue JOIN Issues ON category_issue.issue_id = issues.id
LEFT JOIN issue_subscriptions ON issues.id = issue_subscriptions.issue_id
WHERE category_issue.category_id = 1
GROUP BY issues.id
ORDER BY followers DESC
How would I go about this select using Laravel's fluent query builder? I am aware I can use a raw sql query but I would like to avoid that if possible.
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.