using SUM in whereraw/where in laravel framework - php

I have columns named as PlanCost Discount AmountPaid and a label which contains the Due
Here,I am trying to display only the rows where the PlanCost != AmountPaid
this is my whole query
$getID = isset($inputArray['id']) ? $inputArray['id'] : 0;
$query = TelePlanSelect::join('tele_plan', 'tele_plan.id', '=', 'tele_plan_select.teleplan_id' )
->leftjoin('tele_payment_defs', 'tele_payment_defs.telereg_id', '=', 'tele_plan_select.telereg_id')
->leftjoin('tele_payment_items', function ($join){
$join->on('tele_payment_items.telepaymentdefs_id', '=', 'tele_payment_defs.id')
->on('tele_payment_items.teleplan_id', '=' ,'tele_plan.id');
} )
->selectRaw('tele_plan.id as `PlanID`,' .
'tele_plan.plan_name as `PlanName`,' .
'tele_plan.plan_cost as `PlanCost`,' .
'tele_plan.plan_details as `PlanDetails`,'.
'sum(tele_payment_items.amount) as `AmountPaid` ,'.
'COALESCE(sum(tele_payment_items.discount),0) as `Discount`,'.
'(COALESCE(tele_plan.plan_cost,0) - sum(COALESCE(tele_payment_items.discount,0))) - sum(coalesce(tele_payment_items.amount, 0)) as `Due` '
)
->where('tele_plan_select.telereg_id', $getID)
->groupBy('tele_plan.id')
->where(' tele_plan.plan_cost', '!=', 'sum(tele_payment_items.amount)');
I am not sure whether we can use sum in where/whereraw
Could someone help me?
EDIT 1 :
{"message":"SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select count(*) as aggregate from (select tele_plan.id asPlanID,tele_plan.plan_name asPlanName,tele_plan.plan_cost asPlanCost,tele_plan.plan_details asPlanDetails,sum(tele_payment_items.amount) asAmountPaid,COALESCE(sum(tele_payment_items.discount),0) asDiscount,(COALESCE(tele_plan.plan_cost,0) - sum(COALESCE(tele_payment_items.discount,0))) - sum(coalesce(tele_payment_items.amount, 0)) asDuefromtele_plan_selectinner jointele_planontele_plan.id=tele_plan_select.teleplan_idleft jointele_payment_defsontele_payment_defs.telereg_id=tele_plan_select.telereg_idleft jointele_payment_itemsontele_payment_items.telepaymentdefs_id=tele_payment_defs.idandtele_payment_items.teleplan_id=tele_plan.idwheretele_plan_select.telereg_id= 8 and tele_plan.plan_cost <> sum(tele_payment_items.amount) group bytele_plan.id) as a) # C:\\xampp\\htdocs\\halframework\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:625","status":"failed"}

You can use raw sql functions like sum, but you have to wrap them in laravel's \DB::raw() function so they won't be escaped.
For your Where clause, you should do the following
->where('tele_plan.plan_cost', '<>', \DB::raw('sum(tele_payment_items.amount)'));
You could also use laravel's WhereRaw function to write your own conditions:
->whereRaw('tele_plan.plan_cost <> sum(tele_payment_items.amount)')
Update:
The error stated that there was a problem with the GroupBy. The reason for this is because a sum can only be done after a group by, but a where can't. So, this will have to be added in a HAVING clause.
Replace the where by a having, and this should work:
->havingRaw('tele_plan.plan_cost <> sum(tele_payment_items.amount)');

Related

how to pass a pure sql query to laravel eloquent

This SQL:
SELECT COUNT(*) AS total_see_all_video
from users u
WHERE 7 = (SELECT COUNT(*) FROM lecciones_users lu WHERE lu.uuid = u.uuid)
I tried this code but did not work:
$data = LeccionesUsers::select(
DB::raw('COUNT(*) AS total_ase_vis_videos'),
DB::raw('where 7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
)
->join('users', 'lecciones_users.uuid', '=', 'users.uuid')
->get();
Your issue is that you are not correctly forming your query. You can do ->toSql(); instead of ->get(); and you would see the final SQL (would definitely not be the same as the one you wrote first).
So, you should have this to have the same SQL:
$total_see_all_video = LeccionesUsers::whereRaw('7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
->count();
Please, try my query (and also run ->toSql() to see if you have a correct SQL).
I would still recommend to use relationships and it is very weird to do 7 = query.
You can use
DB::query()->fromSub('Raw sql query here..')
and then can perform actions on this.For the reference you can use the documentation fromSub
You can also look into this convert this where break this query to parts to be used accordingly. You can use this section for the reference purpose:
Laravel-Raw-Expressions
Hope this will help you with the result.

laravel access outer query column inside subquery

I am trying to convert raw sql queries into laravel queries.
Here's the raw query:
select
tsk.id,
tsk.request_id,
tsk.sys_index,
tsk.category_group,
tsk.category,
tsk.is_assigned,
tsk.hash_id
from
user_tasks as usr
inner join
unassigned_tasks as tsk
on usr.task_id = tsk.id
where
usr.assigned_to = 12
AND
tsk.product_id NOT IN ( SELECT product_id FROM product_progresses WHERE request_id = tsk.request_id )
AND
BINARY hash_id NOT IN ( SELECT hash_id FROM product_match_unmatches WHERE request_id = tsk.request_id AND auto_unmatched_by IS NOT NULL )
The laravel query is:
public function getTasks($assigned_to) {
/** fetch products assigned to a specific user token,
* ignore already matched skus, and links that are auto-unmatched
**/
$tasks = DB::table('user_tasks as usr')
->join('unassigned_tasks as tsk', 'usr.task_id', '=', 'tsk.id')
->select('tsk.id', 'tsk.request_id', 'tsk.sys_index', 'tsk.category_group', 'tsk.category', 'tsk.is_assigned', 'tsk.hash_id')
->where('usr.assigned_to', '=', $assigned_to);
$tasks->whereNotIn('tsk.product_id', function($qs) {
$qs->from('product_progresses')
->select(['product_id'])
->where('request_id', '=', 'tsk.request_id')
->get();
});
$tasks->whereNotIn(DB::raw('BINARY `hash_id`'), function($qs) {
$qs->from('product_match_unmatches')
->select('hash_id')
->where('request_id', '=', 'tsk.request_id')
->whereNotNull('auto_unmatched_by')
->get();
});
return $tasks->toSql();
The below query should take tsk.request_id value from outer query, but I think the column value is not passed to it.
Here's the output of toSql():
SELECT `tsk`.`id`,
`tsk`.`request_id`,
`tsk`.`sys_index`,
`tsk`.`category_group`,
`tsk`.`category`,
`tsk`.`is_assigned`,
`tsk`.`hash_id`
FROM `user_tasks` AS `usr`
INNER JOIN `unassigned_tasks` AS `tsk`
ON `usr`.`task_id` = `tsk`.`id`
WHERE `usr`.`assigned_to` = ?
AND `tsk`.`product_id` NOT IN (SELECT `product_id`
FROM `product_progresses`
WHERE `request_id` = ?)
AND BINARY `hash_id` NOT IN (SELECT `hash_id`
FROM `product_match_unmatches`
WHERE `request_id` = ?
AND `auto_unmatched_by` IS NOT NULL)
Note the ? inside where clauses.
The resultset is different from the raw and laravel query.
I even tried see the bindings value:
//dd($tasks->getBindings());
$sql = str_replace_array('?', $tasks->getBindings(), $tasks->toSql());
dd($sql);
And on running this raw query, it is outputting the correct result-set.
UPDATE:
On checking the bindings, here's what I found:
array:3 [▼
0 => 12
1 => "tsk.request_id"
2 => "tsk.request_id"
]
Here outer query column is wrapped inside quotes and hence treated as a string.
So maybe where clause is trying to compare request_id with a string rather than the outer column.
If it is so, then how do I make them treat as columns rather than string?
use DB::raw() where you trying to add value of request_id
Example
AND `tsk`.`product_id` NOT IN (SELECT `product_id`
FROM `product_progresses`
WHERE `request_id` = DB::raw('tsk.request_id'))
whereRaw('pgr.request_id = tsk.request_id');
Solved the string issue.
You should try to remove select() method, in the subquery replace where() method with whereColumn() method and remove get() method:
$tasks = DB::table('user_tasks', 'urs')
->join('unassigned_tasks as tsk', 'usr.task_id', '=', 'tsk.id')
->where('usr.assigned_to', '=', $assigned_to);
Note: i put the alias 'urs' as second argument (view docs)
$tasks->whereNotIn('tsk.product_id', function($qs) {
$qs->from('product_progresses')
->select(['product_id'])
->whereColumn('request_id', 'tsk.request_id');
});
If you want get specific fields, you must specify the fields in get() method:
return $tasks->get(array('tsk.id', 'tsk.request_id', 'tsk.sys_index', 'tsk.category_group', 'tsk.category', 'tsk.is_assigned', 'tsk.hash_id'));

WhereHas with WhereRaw on one to many relationship (Laravel)

I have an order table and an order_details table in my system.
Relationship between order table and order details table is one to many, means One order has many order details.
Now the problem is i am trying to filter the order with the quantity of items a that are stored in order_details table.
what i doing right know trying to access with whereHas
if ($request->has('quantity') && $request->quantity != null){
$query = $query->whereHas('orderDetails',function ($q) use ($request){
$q->whereRaw('SUM(Quantity) >= '.$request->quantity);
});
}
$orders = $query->orderBy('OrderID','desc')->get();
But it throws an error
General error: 1111 Invalid use of group function (SQL: select * from `orders` where `AddedToCart` = 0 and `PaymentSucceeded` = 1 and exists (select * from `order_details` where `orders`.`OrderID` = `order_details`.`OrderID` and SUM(Quantity) >= 12) order by `OrderID` desc)
I will be vary thankful if i get the solution
To be able to use sum function you need to group by data and as I see you are trying to group them by orderID.
An approach like this might help:
$ordersIDs = DB::table('orderDetails')
->groupBy('OrderID')
->havingRaw('SUM(Quantity)', '>=', 12)
->pluck('orderID')->toArray();
$orders = DB::table('orders')
->whereIn($ordersIDs)
->get();
The above code executes two SQL queries, you can mix them easily to make one.
Hope it helps.

laravel eloquent ->whereHas - write your own exists( subquery )

Laravel Eloquent ->whereHas() uses anexists() subquery - https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html - in order to return your results.
I would like to write my own subquery, but I do not know how to tell Eloquent to ->where it.
If I do:
$query->where( DB::raw(' exists( subquery ) ')
Laravel instead writes the subquery as:
where exists( subquery ) is null
So I'm just wondering what $query->method() could be used to add an exists() subquery to the 'where' statements. The subquery would be just the same kind that laravel generates, but written out:
... and exists ( select * from `tbl` inner join `assets` on `custom_assets`.`id` = `tbl`.`asset_id` where `assets`.`deleted_at` is null and `users`.`id` = `assets`.`client_id` and `field_id` = ? and (`value` = ? and `assets`.`deleted_at` is null )
Use whereRaw():
$query->whereRaw('exists( subquery )')
Read WhereHas Description Here
You can find this code example there. You can also add a closure for you custom query in whereHas.
// Retrieve all posts with at least one comment containing words like foo%
$posts = App\Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();

How can I make select in select on laravel eloquent?

I use laravel 5.3
My sql query is like this :
SELECT *
FROM (
SELECT *
FROM products
WHERE `status` = 1 AND `stock` > 0 AND category_id = 5
ORDER BY updated_at DESC
LIMIT 4
) AS product
GROUP BY store_id
I want to change it to be laravel eloquent
But I'm still confused
How can I do it?
In cases when your query is to complex you can laravel RAW query syntax like:
$data = DB::select(DB::raw('your query here'));
It will fire your raw query on the specified table and returns the result set, if any.
Reference
If you have Product model, you can run
$products = Product::where('status', 1)
->where('stock', '>', 0)
->where('category_id', '=', 5)
->groupBy('store_id')
->orderBy('updated_at', 'desc')
->take(4)
->get();
I think this should give you the same result since you pull everything from your derived table.

Categories