I have a query about this project that I am doing, I make a query to my two tables and the data that I call in this case is a quantity number for both, the data displayed is the one that has the same id for both tables.
The problem occurs when I pass two identifiers and to those two identifiers I want to add their current amount with the amount obtained from the other table
In general, what I want to do is add the amounts obtained, this is my code that I am working with, I would really appreciate if you can help me solve it or guide me.
$id_servis = [1077,1078];
$sum_quantity_add = Servis_tareas::where('servis_id',$id_servis)->get();
foreach($sum_quantity_add as $sum_add){
$quantity_two[] = $sum_add->quantity;
}
$quantity_actual = Servis::wherein('id',$id_servis)->get();
foreach($quantity_actual as $quantity_act){
$quantity_one[] = $quantity_act->quantity_final;
}
dd($id_servicios,$quantity_one, $quantity_two);
//ERROR
$total[] = $quantity_one + $quantity_two;
//ERROR
if(is_numeric($total) < 0 ){
Servis::wherein('id',$id_servis)->update(['quantity_final' => 0]);
}else{
Servis::wherein('id',$id_servis)->update(['quantity_final' => $total]);
}
My Answer:
There are a couple of issues in your code that need to be addressed.
Firstly, when you are fetching data from the database using the `wherein` method, you need to pass an array of values instead of a single value. So, you should change `$id_servis` to an array like this:
php
$id_servis = [1077, 1078];
Next, when you are trying to calculate the total quantity, you need to sum the corresponding quantities from both tables. You can do this inside the loop where you are fetching the quantities like this:
php
$total = [];
foreach($quantity_actual as $key => $quantity_act){
$total[$key] = $quantity_act->quantity_final + $quantity_two[$key];
}
Then, you can check if the total quantity is less than 0 and update the database accordingly:
php
foreach($total as $key => $value){
if($value < 0){
Servis::where('id', $id_servis[$key])->update(['quantity_final' => 0]);
} else {
Servis::where('id', $id_servis[$key])->update(['quantity_final' => $value]);
}
}
This way, you are calculating the total quantity correctly and updating the database based on the calculated total.
Rate this post
3 of 5 based on 6427 votesComments