I am trying to implement this query in Laravel
"SELECT * FROM jobs
WHERE status = 1 AND
taskerCount = (SELECT count(*) FROM jobRequests WHERE status = 1 AND job_id =
jobs.id)"
This is what i have tried;
Auth::user()->jobs
->where('status', 1)
->where('taskerCount', function ($q) {
$q->where('status', 1)
->where('job_id', $q->id)->count();
});
But I get the error:
Object of class Closure could not be converted to int.
Use a raw expression instead of -count().
You can view this documentation here
Example of a raw query from laravel:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Make sure you define the count as a name.
Related
I have this query, but it does not work
$order = Order::select('*', DB::raw('count(*) as num_product'),
DB::raw('count(status) where status = 1 as accepted')) // ERROR HERE
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))->get();
I want to show number of order that accepted, for example : 2 of 5
$order = Order::select(DB::raw('count(*) as num_product, status'))
->where('status', 1)
->groupBy('status')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->get();
I'm trying to rewrite this SQL query but I'm stuck at this point
The query is meant to join the projects table to the project_progress table by using a sub-query to only join on the latest entry
SELECT * FROM projects
JOIN project_progress ON project_progress.id =
(
SELECT id FROM project_progress
WHERE project_progress.project_id = projects.id
ORDER BY project_progress.created_at DESC
LIMIT 1
)
WHERE project_progress.next_action_date < NOW()
AND projects.status != 'Complete'
AND projects.member_id = 1
ORDER BY projects.title ASC
To:
$projects = App\Project::where('member_id', 1)
->join('project_progress', function ($join) {
$join->on('project_progress.id', '=', function ($query) {
$query->select('project_progress.id')
->from('project_progress')
->where('project_progress.project_id', 'projects.id')
->orderBy('project_progress.created_at', 'desc')
->limit(1);
});
})
->where('project_progress.next_action_date', '<', Carbon\Carbon::now())
->notCompleted()
->orderBy('projects.project_title', 'asc')
->get();
I think some thing is wrong with this line but I'm not sure how to write it
$join->on('project_progress.id', '=', function ($query) {
ErrorException (E_ERROR) strtolower() expects parameter 1 to be string, object given \vendor\laravel\framework\src\Illuminate\Database\Grammar.php
Use where():
$join->where('project_progress.id', '=', function ($query) {
I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres
I have three tables as below:
users
id|name|username|password
roles
id|name
users_roles
id|user_id|role_id
These tables communicate via belongsToMany.
I would like to find a way to select all data in “users” table except ones that their user value of "role_id" is 5 in table “users_roles”.
How can I do it?
You should use whereDoesntHave() to select models that don't have a related model meeting certain criteria:
$users = User::whereDoesntHave('roles', function($q){
$q->where('role_id', 5);
})->get();
Use Laravel's Query Builder:
<?php
$users = DB::table('users')
->leftJoin('users_roles', 'user.id', '=', 'users_roles.user_id')
->where('users_roles.role_id', '!=', 5)
->get();
http://laravel.com/docs/4.2/queries
Or using Eloquent directly:
<?php
$users = User::whereHas('users_roles', function($q)
{
$q->where('role_id', '!=', 5);
})->get();
http://laravel.com/docs/4.2/eloquent#querying-relations
<?php
$users = User::whereHas('roles', function($query) {
$query->where('id', '<>', 5);
})
->orHas('roles','<', 1)
->get();
I think the correct answer is:
User::whereHas('roles', function ($query) {
$query->whereId(5)
}, '=', 0)->get();
This code should send a query that checks if the role with id=5 is related to the user or not.
Edit
While I think this should work but the #lukasgeiter answer is preferable.
In the end both methods use the has() to count the related models by using a subquery in the db query where clause but when you use the whereDoesntHave() it specifies the operator < and the count 1 itself.
You can var_dump(DB::getQueryLog()) in App::after()'s callback to see the actual query.
I'm using SQLite with my Laravel app and trying to run a whereHas query:
$payments = Payment::whereHas('payers', function($q){
$q->where('user_id', '=', 1);
})->get();
This returns an empty result and is due to the integer 1 being cast to a string as evidenced by the resulting query generated by laravel/eloquent:
select * from "payments" where (select count(*) from "payers" inner join "payer_payment" on "payers"."id" = "payer_payment"."payer_id" where "payer_payment"."payment_id" = "payments"."id" and "user_id" = 1) >= '1'
Having reviewed this github issue I tried using DB::raw like so:
$payments = Payment::whereHas('payers', function($q){
$q->where('user_id', '=', DB::raw(1));
})->get();
But no improvement. How can I fix this without changing database driver?
$payments = Payment::whereHas('payers', function($q){
$q->where('user_id', '=', 1);
}, '>=', DB::raw(1))->get();