I have a primary query which will run following way. And I had to check a condition and if the condition fulfilled it will add a statement with the existing query. But it doesn't work in right way means i couldn't get the orderby function run with the existing one? Why's that or how to solve this?
$query = DB::table('users')
->join('products','products.auth_id','users.id')
->Join('reviews','products.id','reviews.product_id')
->select('products.*','users.avatar',DB::raw('(sum(rating)/count(user_id)) as rating'))
->where('products.status','=','1')
->groupBy('products.id')
->latest();
if($request->get('dropdown')!='0' && $request->get('dropdown')=='desc')
{
$query->orderBy('products.regular_price', 'desc') ;
}
$products = $query->get();
Try this
if($request->get('dropdown')!='0' && $request->get('dropdown')=='desc')
{
$query = $query->orderBy('products.regular_price', 'desc') ;
}
Note : You have added latest() function in your query. This function added following in your query
ORDER BY created_at DESC
Default parameter of latest() is created_at
Related
My query (DB::raw(AVG('pt.progress'))) this part is throwing error at the moment
$query = DB::table('projects as p')
->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
->select(
'p.id', 'p.project_name', DB::raw(AVG('pt.progress')) //this is where I need the average
);
$query->orderBy($order, $dir);
if ($limit != -1) {
$query->skip($start)->take($limit);
}
$records = $query->get();
Table structure:
projects:
========
id
project_name
...
...
projects_tasks:
===============
id
project_id,
parent, //0 or 1
progress //exmaple value 0.00 to 1.00
How to get the average of progress, where parent_id = 0 and project_id is the same?
The following query does work if I create a function and pass it in a loop, however, I want to optimize it and run it by joining on above query.
$data_row = DB::table('projects_tasks')
->select(DB::raw('(SUM(progress)*100)/count(progress) as project_progress'))
->where(['project_id' => $project_id, 'parent' => 0])
->get();
Seems that you have a syntax error on your query, the problem is in here DB::raw(AVG('pt.progress')).
Since you're using a raw query, the parameter there should be a string, so you must enclose that in quotes / double qoute.
$query = DB::table('projects as p')
->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
->select(
'p.id', 'p.project_name', DB::raw("AVG('pt.progress')")
);
$query->orderBy($order, $dir);
if ($limit != -1) {
$query->skip($start)->take($limit);
}
$records = $query->get();
I want to get count from 'user' table with 'plan_validity' is null or more than today's date. both condition need to check for same column with user_id and status = 1.
$currentUser = User::where('user_id', $card_details->user_id)
->where('status', 1)
->where(function (Builder $query) {
return $query
->whereDate('plan_validity', '>=', Carbon::now())
->orWhere('plan_validity', null);
})->count();
giving error
[2021-11-23 10:40:31] production.ERROR: Argument 1 passed to App\Http\Controllers\ProfileController::App\Http\Controllers\{closure}() must be an instance of App\Http\Controllers\Builder, instance of Illuminate\Database\Eloquent\Builder given, called in /home/hellovcard/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 237 {"userId":17,"exception":"[object] (TypeError(code: 0): Argument 1 passed to App\\Http\\Controllers\\ProfileController::App\\Http\\Controllers\\{closure}() must be an instance of App\\Http\\Controllers\\Builder, instance of Illuminate\\Database\\Eloquent\\Builder given, called in /home/hellovcard/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 237 at /home/hellovcard/public_html/app/Http/Controllers/ProfileController.php:34)
how to modify above mentioned query?
this is output I need to get
enter image description here
You are not combining your "where" clauses properly. With the "orWhere" at the end, it essentially ignores all the conditions (ie. which user it relates to) of the preceding where clauses, so adds to the results any row where plan_validity is null. So after you query by user ID and status, you then need to combine the remainder of the query into a logical group like so :
$user = Users::where('user_id', $card_details->user_id)
->where('status', 1)
->where(function (Builder $query) {
return $query
->whereDate('plan_validity', '>=', Carbon::now())
->orWhere('plan_validity', null);
})
->get();
I have:
$buyingNet = DB::table('parts_enquiries_buying AS PEB')
->select(DB::raw('SUM((PEB.quantity*PEB.net)/IF(ISNULL(currencyRate), rate, currencyRate)) AS total'))
->join('currencies_rates AS CR', function ($q) {
$q->on('CR.id', '=', 'PEB.currencyId')
//->where(DB::raw('YEAR(CR.date)'), '=', date('Y'))
->where(DB::raw('MONTH(CR.date)'), '=', date('m'));
})
->leftJoin('jobs', 'jobs.enquiryId', '=', 'PEB.enquiryId')
->leftJoin('invoices_out AS IO', 'IO.jobId', '=', 'jobs.id')
->where('PEB.enquiryId', $enquiryId)
->first()->total;
If I uncomment the where that matches the year I get null returned, but all the rows that should be there are there.
Is my syntax correct? It should translate as:
... YEAR(CR.date) = ? AND MONTH(CR.date) =? ...
I believe the issue here is that Query builder doesn't understand your DB::raw statement within the ->where clause.
You should do as folllows:
->whereRaw("YEAR(CR.date) = '". date('Y')."'")
->whereRaw("MONTH(CR.date) = '". date('n')."'")
for the month clause you need to use n instead of m since MySQL MONTH returns a single digit for months below 10.
I've been able to get the query result I need using the following raw sql:
select `person`.`id`, `full_name`, count(actions.user_id) as total
from `persons`
left join `actions`
on `actions`.`person_id` = `persons`.`id`
and `actions`.`user_id` = $user
where `type` = 'mp'
group by `persons`.`id`
But I haven't been able to get it working in eloquent yet.
Based on some similar answers, I'd tried functions within ->where() or leftJoin(), but the count of each person's actions isn't yet being filtered by $user. As it stands:
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', 'persons.id')
->where('actions.user_id', $user);
})
->groupBy('persons.id')
->where('type', 'foo')
//->where('actions.user_id', '=', $user)
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
I'm at least heading in roughly the right direction, right...?
If it's relevant, the Persons.php model has two actions relationships:
public function actions()
{
return $this->hasMany('Action');
}
public function actionsUser($id)
{
return $this->hasMany('Action')->where('user_id', $id);
}
So, for reference, I solved it like so:
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', '=', 'persons.id')
->where('actions.user_id', '=', "$user");
})
->groupBy('persons.id')
->where('type', 'foo')
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
The ->where() clause within leftJoin, oddly, needs the speech marks for the variable to be passed through the sql query correctly (likewise, '2' doesn't seem to work while "2" does).
I found that the where doesn't always work on the leftJoin clause
If in the future you get any trouble with it, I'd suggest you using this:
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', '=', 'persons.id')
->on('actions.user_id', '=', "$user");
})
->groupBy('persons.id')
->where('type', 'foo')
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
Hope it helps someone.
When laravel eloquent just start getting complex like this
For more flexibility and readability I'll just use plain sql statement then hydrate the results.
$sql = "
SELECT `person`.`id`,
`full_name`,
count(actions.user_id) AS total
FROM `persons`
LEFT JOIN `actions`
ON `actions`.`person_id` = `persons`.`id`
AND `actions`.`user_id` = $user
WHERE `type` = 'mp'
GROUP by `persons`.`id`
";
$query = Person::hydrate(
DB::select( $sql )
);
I'm using the Laravel query builder to dynamically filter data based on a user's filter selections:
$query = DB::table('readings');
foreach ($selections as $selection) {
$query->orWhere('id', $selection);
}
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');
When I examine the SQL, I get something like this:
select count(*) as `count` from `readings` where `id` = 1 or id` = 2 and `date` between "2013-09-01" and "2013-09-31" group by `id`;
But what I need is something like this (with brackets around the or statements):
select count(*) as `count` from `readings` where (`id` = 1 or id` = 2) and `date` between "2013-09-01" and "2013-09-31" group by `id`;
How do I add brackets around WHERE conditions with Laravel query builder?
Very useful, I use this:
->where(function ($query) use ($texto){
$query->where('UPPER(V_CODIGO)', 'LIKE', '%'.Str::upper($texto).'%')
->orWhere('UPPER(V_NOMBRE)', 'LIKE', '%'.Str::upper($texto).'%');
});
I couldn't find this in documentation, whereNested was what I was looking for. Hope it helps anybody.
$q->whereNested(function($q) use ($nameSearch) {
$q->where('name', 'LIKE', "%{$nameSearch}%");
$q->orWhere('surname', 'LIKE', "%{$nameSearch}%");
});
Note: This is on Laravel 4.2
Solved this myself by using a closure, as described in Parameter Grouping in the query builder documentation.
$query = DB::table('readings');
$this->builder->orWhere(function($query) use ($selections)
{
foreach ($selections as $selection) {
$query->orWhere('id', $selection);
}
});
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');
Sometimes you may need to group several "where" clauses within parentheses in order to achieve your query's desired logical grouping. In fact, you should generally always group calls to the orWhere method in parentheses in order to avoid unexpected query behavior. To accomplish this, you may pass a closure to the where method:
$users = DB::table('users')
->where('name', '=', 'John')
->where(function ($query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();
As you can see, passing a closure into the where method instructs the query builder to begin a constraint group. The closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')
You can use WHERE IN here for the same effect:
$query = DB::table('readings');
$query->whereIn('id', $selection)
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');