Get SUM form last 2 rows input with laravel - php

i have table like this:
enter image description here
i want get sum from field 'total' from last 2 rows input,
this my code :
$data = DB::table('packagings')->where('plant',$pt->plant)->orderBy('id','desc')->limit(2)->sum('total');
but my code get all sum from field 'total'

Mysql will sum total from table packagings firstly that will become one record, and then take 2 records from one record. So it always return all sum from field total.
Collection way:
$data = DB::table('packagings')->where('plant',$pt->plant)->latest()->take(2)->get()->sum('total');
Query Builder way:
$sub = DB::table('packagings')->where('plant',$pt->plant)->latest()->take(2);
$data = DB::table(DB::raw("({$sub->toSql()}) AS sub"))->mergeBindings($sub)->sum('total');

Related

Randomly select multiple rows and randomly update multiple rows between 2 tables (Laravel eloquent)

I have a situation like this
My mysql has 2 tables product_queue and description
I want to randomize multiple rows of content of column 'content' in descripton table to randomly update multiple rows into 'descripton' column of product_queue table provided that store_id column of 2 tables must be equal
Image description table
Image Product_queue table
I tried this code but it didn't
$descriptions = DescriptionModel::orderByRaw("RAND()")->get();
foreach ($descriptions as $description) {
ProductQueue::where('store_id', $description->store_id)
->update(['description' => $description->content]);
}
Before I ask a question, I have also tried on the forum
use this to get random records from db
$data = DB::table('table_name')->inRandomOrder()->limit(50)->get();
Try this:
$descriptions = DescriptionModel::inRandomOrder()->get();
$descriptions = DescriptionModel::inRandomOrder()->limit(20)->get(); // get 20 random records
or:
$descriptions = DescriptionModel::all()->random();
$descriptions = DescriptionModel::all()->random(20); // get 20 random records

How to get the count of a specif value from a single column

I was working with a project where I want to get the count of values in a column. I will explain with an example.
I have a table column named name. Where it's values are A,B,C,D,A,D,B,A,C.
Now I want the output as
Count: A-3,B-2,C-2,D-2.
I have tried using group by and distinct. but both don't give me what I want. It all getting the total count of that item. In the code given below is the query I tried. There I want the count of particulars_id and the $public_page_id will be common for all particulars_id I am fetching. There will be a number of public_page_id in the table, and each will have some particulars_id under them.
$output = '';
$this->db->select('COUNT(service_appointment_details.particulars_id)
as count,particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_id');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db-
>join('service_appointment_details','particulars.public_page_id =
service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Expected Result
Expected Result is (based on the above example)
Count: A-3,B-2,C-2,D-2.
Actual Result
But what I'm getting now is
Count: A-9,B-9,C-9,D-9.
I need to fetch count of each particulars_id under the given public_page_id
You should use count(*)
$this->db->select('COUNT(*) as count,particulars.particulars_name');
........
As pointed out by #scaisEdge, you need to use count(*) instead of count(service_appointment_details.particulars_id). By using count(service_appointment_details.particulars_id), you basically count the number of rows from your select which is not what you want.
Final snippet would be:
$output = '';
$this->db->select('COUNT(*) as count, particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_name');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db->join('service_appointment_details','particulars.public_page_id = service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Whenever you want to count occurrence of a column values, you'd do
SELECT column_to_count, count(*) FROM table GROUP BY column_to_count

Get total value of one column from a collection

I have an orders table which holds orders.
Each orders can have supplements.
The relation is accessed via
$order->supplements;
Theres a column on the supplements table called 'unit_price'.
How do I get the total price of all supplemented combined?
Try using the laravel sum query.
$total = $order->supplements->sum('unit_price');
Should give you the total price
Try using sum aggregates()
$totalPrice = $order->sum(function ($query) {
return $query->supplements->sum('unit_price');
});

Selecting and updating any number of rows in large table using CodeIgniter

I've got a large table, about 10 million rows, and I'm trying to build a function that selects a random number of rows (anything between 1 and all), updates a field on the selected rows to x (winner) and updates the field on remaining rows to y (loser).
All rows have a unique id but not all rows will be selected from (the table has competition entries for a number of competitions but the function needs to select winners for one competition only).
I've considered ordering by random but it's too slow for a big table.
I've also considered assigning a random value into the row when it's inserted into the table so that it can be used to order but it would have to be unique and there can be batch updates for thousands of rows so it would be slow to assign a unique random value to each row.
There's too much data to save the result as an array and shuffle.
Can anyone suggest other solutions?
This is how I would do it if the table wasn't huge:
function getWinnersLosers($winnercount,$allwinners) {
// Must have draw id and ticketstatus id
if ( ! $this->draw_id || ! $this->ticketstatus_id ) return false;
// Update winners
$this->db->where('draw_id', $this->draw_id);
$this->db->where('ticketstatus_id', CONST_TICKETSTATUS_ENTERED);
$this->db->order_by('id', 'RANDOM');
if ( ! $allwinners ) $this->db->limit($winnercount);
$data = array( 'ticketstatus_id' => CONST_TICKETSTATUS_WINNERUNCLAIMED );
$query = $this->db->update('drawtickets',$data);
// Update losers (remaining tickets)
$this->db->where('draw_id', $this->draw_id);
$this->db->where('ticketstatus_id !=', CONST_TICKETSTATUS_WINNERUNCLAIMED);
$data = array( 'ticketstatus_id' => CONST_TICKETSTATUS_LOSE );
$query = $this->db->update('drawtickets',$data);
}

ID from array NOT in table

It seems that I have to edit my question again - these down votes are getting frustrating...
I have an array of ids and a table to check it with. This is the query I use:
SELECT COUNT(*) FROM orders WHERE order_id IN (...
When this number isn't equal to the number of ids in the array, I need to get those values from the array that I have, that do not exist in the table. Is there a more optimal way to do this than making some temporary table, and selecting from it?
EDIT: For all those suggesting inserting NOT in the first query - I do not need all the rows from my table that do not match the values in the array - I need the values from the ARRAY itself...
For example, I have an array of three ids - "1","2","3". In the table I have ids "2" and "3". I check the array with my query:
SELECT COUNT(*) FROM orders WHERE order_id IN (1,2,3)
I get the number 2 as a result of this query, and that doesn't match the number of ids I have in the array, which is 3. I need a query that will get the missing id from the array I submitted, in this case the id I need is "1"
I don't think there's a clean SQL-only solution, because there's no way to SELECT from an array. However, instead of using a temporary table, you could return all the IDs that are found in the table, and do the NOT on the PHP side.
So select the result of this into an array, $existing_orders:
SELECT order_id FROM orders WHERE order_id IN (...);
Then you have:
$all_orders = array(1, 2, 3); // IDs you're looking for
$existing_orders = array(2, 3); // IDs that were found in the table
$not_existing_orders = array_diff($all_orders, $existing_orders);
print_r($not_existing_orders); // Array( [0] => 1 )
OK THAT´S clear now:
Then you will have to make something like this:
select id from order where id IN ( your list )
create a second array with the found values
and then use php array function array_diff
select * from orders where order_id NOT in (...

Categories