How to skip a row with file exists condition in laravel - 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.

Related

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();

Only one row is returned using where in with comma seperated value in Laravel raw query

I am developing a php project using Laravel 5.2. In my app I am retrieving records from database using manual query. But I am having a problem with retrieving records by using where in statement with csv.
Example how I am retrieving
$csv = "1,3,5";
$sql = "SELECT * FROM `items` WHERE `id` IN (?)";
$rows = DB::select($sql,[$csv]);
As you can see above I am retrieving three rows. But it returns only one row where id is 1. Why is that?
You can't do it like that. Each entry in your csv is a separate parameter, so for your code you would actually need IN (?, ?, ?), and then pass in the array of values. It would be pretty easy to write the code to do this (explode the string to an array, create another array of question marks the same size, put it all together).
However, you are using Laravel, so it would be easier to use the functionality Laravel provides to you.
Using the query builder, you can do this like:
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// get the data
$rows = DB::table('items')->whereIn('id', $ids)->get();
// $rows will be an array of stdClass objects containing your results
dd($rows);
Or, if you have an Item model setup for your items table, you could do:
$items = Item::whereIn('id', $params)->get();
// $items will be a Collection of Item objects
dd($items);
Or, assuming id is the primary key of your items table:
// find can take a single id, or an array of ids
$items = Item::find($params);
// $items will be a Collection of Item objects
dd($items);
Edit
If you really want to do it the manual way, you could use a loop, but you don't need to. PHP provides some pretty convenient array methods.
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// generate the number of parameters you need
$markers = array_fill(0, count($ids), '?');
// write your sql
$sql = "SELECT * FROM `items` WHERE `id` IN (".implode(',', $markers).")";
// get your data
$rows = DB::select($sql, $ids);

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

$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);

Vtiger select query

I'm copying a vtiger query in a similar way but there is one change that the query given first having only one output so there is kept 0 in 2nd argument,
but in my customized query there are multiple outputs so what should I kept instead of 0
both are given as below:
original query
$is_recurring_event_query = $adb->pquery('SELECT recurring_group_id from vtiger_activity where activityid=?',array($id));
$is_recurring_event = $adb->query_result($is_recurring_event_query,0,'recurring_group_id');
copying it to use at different way
$is_recurring_event_activity_query = $adb->pquery('SELECT activityid from vtiger_activity where recurring_group_id='.$is_recurring_event);
$is_recurring_event_activity = $adb->query_result ($is_recurring_event_activity_query,0,'activityid');
You have to put variable and have to use for loop for your query to execute and get multiple values.
Suppose your query is like this
$result = $adb->pquery ('SELECT * from vtiger_activity where id='.$recordId);
$noofrow = $adb->num_rows($result );
for($i=0; $i<$noofrow ; $i++) {
$Data['activityid']=$adb->query_result($result,$i,'activityid');
$Data['activityname']=$adb->query_result($result,$i,'activityname');
}
Here in $Data you will get an array of the values.

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