Using whereIn method to return multiple results for the same array value but at different index - laravel

$pidArray contains product ID's, some of those product ID's can be the same. I.E: 34 34 56 77 99 34. As is, it appears the whereIn method does not return results for a productId it has already found in $pidArray, even if it has a different index.
$productDataForOrder = Product::whereIn('id', $pidArray)->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
$productDataForOrder now contains product data, but only for unique ProductID's in $pidarray. So when sum function is run, the sum is wrong as it does not take into account the price for multiple instances of the same productID.
The following code also does not return objects for every product ID in the array which are the same. So if $pidArray contains three identical product ID's, the query will only return a collection with one object, instead of three.
$query = Product::select();
foreach ($pidArray as $id)
{
$query->orWhere('id', '=', $id);
}
$productDataForOrder = $query->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');

You're not going to be able to get duplicate data the way that you're trying. SQL is returning the rows that match your where clause. It is not going to return duplicate rows just because your where clause has duplicate ids.
It may help to think of it this way:
select * from products where id in (1, 1)
is the same as
select * from products where (id = 1) or (id = 1)
There is only one record in the table that satisfies the condition, so that is all you're going to get.
You're going to have to do some extra processing in PHP to get your price. You can do something like:
// First, get the prices. Then, loop over the ids and total up the
// prices for each id.
// lists returns a Collection of key => value pairs.
// First parameter (price) is the value.
// Second parameter (id) is the key.
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
// I used array_walk, but you could use a plain foreach instead.
// Or, if $pidArray is actually a Collection, you could use
// $pidArray->each(function ...)
$total = 0;
array_walk($pidArray, function($value) use (&$total, $prices) {
$total += $prices->get($value, 0);
});
echo $total;

The whereIn method only limits the results to the values in the given array. From the docs:
The whereIn method verifies that a given column's value is contained within the given array
Id make a query variable and loop through the array adding to the query variable in each pass. Something like this:
$query = Product::select();
foreach ($pidArray as $id)
{
$query->where('id', '=', $id);
}
$query->get(['id','price']);

Here is a code that would work for your use case expanding on #patricus
You first fetch an array of key as id and value as price from the products table
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
$totalPrice = collect([$pidArray])->reduce(function($result, $id) use ($prices) {
return $result += $prices[$id];
}, 0);

Related

Eloquent - Detect multiple column duplicate data

I have a table that has 3 column id, sub_id, name. That is a pretty big table and there are some duplicates.
What is the best way to detect the duplicates so that I can remove them?
I tried this but it returns everything (I guess thinking ids are making them non-unique)
$collection = \App\MyModel::all();
$colUnique = $collection->unique(['name', 'sub_id']);
$dupes = $collection->diff($colUnique);
I want to get the models that has same name and sub_id.
id sub_id name
1 2 John
2 2 John <- duplicate
3 2 Robin <- unique
My best bet would be DB::Query.
Step 1: Fetch data by group by
$uniqueData = DB::table('TABLE_NAME')
->groupBy(['sub_id', 'name'])
->select('id')
->toArray();
Step 2: Delete duplicate record.
$noOfDeletedRecords = DB::table('TABLE_NAME')
->whereNotIn($uniqueData)
->delete();
Benefits:
1. Only 2 Queries
2. Better performance over collection.
You can utilize Collection.groupBy method.
$collection = \App\MyModel::all();
$collection
// Group models by sub_id and name
->groupBy(function ($item) { return $item->sub_id.'_'.$item->name; })
// Filter to remove non-duplicates
->filter(function ($arr) { return $arr->count()>1; })
// Process duplicates groups
->each(function ($arr) {
$arr
// Sort by id (so first item will be original)
->sortBy('id')
// Remove first (original) item from dupes collection
->splice(1)
// Remove duplicated models from DB
->each(function ($model) {
$model->delete();
});
})

get all rows in single query with multiple id

I have a asset_request table with fields id and request_id.
I want to select multiple rows with specific ids.
$ids = $request->ids // 5,6
I want to select only rows with ids of 5 and 6 in request table
$ids = $request->ids;
$asset_request = asset_request::whereIn('id',array($ids))->first(); //gets only 6th row.
I need to get all rows matching the given ids.
To clarify after a chat discussion with the Op:
The Op was passing back a string request, therefore, the Op needed to change the following:
$id = $request->id;
$ids = str_split(str_replace(',', '', $id));
$asset_request = asset_request::whereIn('id', $ids)->get();
First you are calling the first method which will return only the first row matched.
You need to call get method to get all rows matched.
Secondly if you are sending ids as a comma separated string you need to convert it to array using explode.
$ids = $request->ids;
$asset_requst = asset_request::whereIn('id', explode(",", $ids))->get();
DB::table('asset_request')
->whereIn('id', (array) $request->ids)
->get();
or
TableModel::whereIn('id', (array) $request->ids)->get();

How to order by value when i get results in array?

I get all tags and its look like this :
"testeng" => 0
"testeng1" => 5
So what i want to do is order this by value so that first one is this with value 5. Any suggestion how can i do this?
$tags = ATags::with('articles')->whereHas('language',function($query) use($current_language_id){
$query->where('id','=',$current_language_id);
})->get();
$count_tag = [];
foreach($tags as $tag){
$count_tag[$tag->name] = $tag->articles->count();
}
You can use arsort() as:
arsort($count_tag)
arsort — Sort an array in reverse order and maintain index association
OR
You can use withCount to sort the result directly in query as:
$tags = ATags::with('articles')
->whereHas('language',function($query) use($current_language_id){
$query->where('id','=',$current_language_id);
})
->withCount('articles')
->orderBy('articles_count', 'desc')
->take(5)
->get();
From the docs
If you want to count the number of results from a relationship without
actually loading them you may use the withCount method, which will
place a {relation}_count column on your resulting models.
You can use Collection's sortBy or sortByDesc & count methods to sort your results like this:
$tags = ATags::with('articles')->whereHas('language',function($query) use($current_language_id) {
$query->where('id','=',$current_language_id);
})
->get()
->sortByDesc(function($tag) { // <---- sorting it via article's count
return $tag->articles->count();
})
->take(5); // <----- fetch largest 5 from collection
You can pass a closure method to sortBy or sortByDesc collection's methods to manipulate your results.

How to skip a row with file exists condition in laravel

This is for a search query based on many input fields, i'm doing if statements inside the query based on the inputs, for example :
$query = Model::all();
if($field = Input::get('field'))
$query->where('column_name', $field);
but what i want to do also is a condition to skip a row if there is no image with a name of that row id, like so :
if( file_exists('/img/'.$this_query->id) )
$query->skip();
Option 1: would be to make an array of the filenames, then utilize the whereIn query builder method, which checks for the occurrence of a column value in an array.
$query = Model::query();
$filenames = scandir('/img');
// the following excludes any id's not in the $filenames array
$query = $query->whereIn('id', $filenames);
Option 2: Run the query and then filter the resulting Collection in Laravel.
$query = Model::query();
// ... then build up your query
// the following gets the query results and then filters them out
$collection = $query->get()->filter( function($item) {
return file_exists('/img/'.$item->id);
}
Rationale: the database cannot check the filesystem during it's processing; so you either need to (Option 1) provide it a list from which to check, or (Option 2) do the checking after you get() the results back from the query.

Codeigniter Pagination: Run the Query Twice?

I'm using codeigniter and the pagination class. This is such a basic question, but I need to make sure I'm not missing something. In order to get the config items necessary to paginate results getting them from a MySQL database it's basically necessary to run the query twice is that right?
In other words, you have to run the query to determine the total number of records before you can paginate. So I'm doing it like:
Do this query to get number of results
$this->db->where('something', $something);
$query = $this->db->get('the_table_name');
$num_rows = $query->num_rows();
Then I'll have to do it again to get the results with the limit and offset. Something like:
$this->db->where('something', $something);
$this->db->limit($limit, $offset);
$query = $this->db->get('the_table_name');
if($query->num_rows()){
foreach($query->result_array() as $row){
## get the results here
}
}
I just wonder if I'm actually doing this right in that the query always needs to be run twice? The queries I'm using are much more complex than what is shown above.
Unfortunately, in order to paginate you must know how many elements you are breaking up into pages.
You could always cache the result for the total number of elements if it is too computationally expensive.
Yeah, you have to run two queries, but $this->db->count_all('table_name'); is one & line much cleaner.
Pagination requires reading a record set twice:
Once to read the whole set so that it can count the total number records
Then to read a window of records to display
Here's an example I used for a project. The 'banner' table has a list of banners, which I want to show on a paginated screen:
Using a public class property to store the total records (public $total_records)
Using a private function to build the query (that is common for both activities). The parameter ($isCount) we pass to this function reduces the amount of data the query generate, because for the row count we only need one field but when we read the data window we need all required fields.
The get_list() function first calls the database to find the total and stores it in $total_records and then reads a data window to return to the caller.
Remember we cannot access $total_records without first calling the get_list() method !
class Banner_model extends CI_Model {
public $total_records; //holds total records for get_list()
public function get_list($count = 10, $start = 0) {
$this->build_query();
$query = $this->db->get();
$result = $query->result();
$this->total_records = count($result); //store the count
$this->build_query();
$this->db->limit($count, $start);
$query = $this->db->get();
$result = $query->result();
return $result;
}
private function build_query($isCount = FALSE) {
$this->db->select('*, b.id as banner_id, b.status as banner_status');
if ($isCount) {
$this->db->select('b.id');
}
$this->db->from('banner b');
$this->db->join('company c', 'c.id = b.company_id');
$this->db->order_by("b.id", "desc"); //latest ones first
}
And now from the controller we call:
$data['banner_list'] = $this->banner_model->get_list();
$config['total_rows'] = $this->banner_model->total_records;
Things get complicated when you start using JOINs, like in my example where you want to show banners from a particular company! You may read my blog post on this issue further:
http://www.azmeer.info/pagination-hitting-the-database-twise/

Resources