WhereBetween not working in laravel 5.2 - php

I am using laravel framework but in this WhereBetween not working. i am using price range where price starts form 1 to 500. when i set price 1-100
it gives me all the records that is in beetween 1 to 100 i.e. 20,40,50 etc. When i change the value from 1- 150 the above result will not be displayed it gives me no result(20,40,50). Can anyone help me . Here is my Code
enter code here
$products = Product::with("productimages")
->whereBetween('price',[$data['from'], $data['to']])
->get();
Note:- $data['from'] start value i.e 1 and $data['to'] end value i.e 150 or more

I just had the same issue. When the data type of the value is not an integer, it will behave very unpredictably. So the solution is to either change the datatype of the column or cast it while fetching, like this:
$from = $data['from'];
$to = $data['to'];
$products = Product::with("productimages")
->whereRaw("CAST(price AS UNSIGNED) BETWEEN ${from} AND ${to}")
->get();
I actually had this issue on the PostgreSQL jsonb data type, as it always returns nested values as strings, and between fetching doesn't work properly.

Using Where Between
$projects = Product::where('created_at', '>', $data['from'])
->where('created_at', '<', $data['to'])
->get();
OR
$current = Product::with("productimages")
->whereBetween('created_at', array($data['from'], $data['to']))->get();
OR
DB::table('Product')->whereBetween('created_at', array($data['from'], $data['to']))->get();

Related

Bifurcate data which I get from an Object and having used take() in Laravel?

What I need:
I have to get exactly 25 data from a query, and for that I have used take(25), which gives me 25 data in an object because I am passing $data as an object there.
The problem is, that I have to get exact 7 data between the price(one of my columns) range $20-$25,
and the other 18 data should be greater than $25, and I am unable to bifurcate the data that I receive as an object.
What I have done till now:
I have tried a lot of things and implemented a lot of functionalities using different functions like:
array_chunk, array_slice, array_merge, etc.
But still, I am not able to get the data in the format that I need.
I hope someone comes up with an appropriate solution.
And for that, Thanks in advance.
$data = DB::table('websites')->selectRaw('websites.*,ads.user_id,ads.meta_value,CASE WHEN ads.meta_value THEN (CEILING(((ads.meta_value*websites.publishing_price/100)+websites.publishing_price ))) ELSE (CEILING(((0*websites.publishing_price)+websites.publishing_price))) END As original_publishing_price,CASE WHEN ads.meta_value THEN (select COUNT(order_attributes.website_id) from order_attributes WHERE order_attributes.website_id = websites.id AND order_attributes.status = 6 AND DATE(`order_attributes`.`created_at`) >= "' . $first_day_prev . '" AND DATE(`order_attributes`.`created_at`) <= "' . $last_day_prev . '" ) END AS total_orders')
->join('admin_settings as ads', function ($join) {
$join->where('ads.user_id', '=', '1')->where('ads.meta_key', '=', "str_commission");
})
->join('users', 'users.id', 'websites.publisher_id')
->where('websites.status', Websites::STATUS_APPROVED)
->where('users.vacation_mode', '0')
->where('websites.is_process', '=', websites::PROCESS_COMPLETE)
->where('websites.deleted_at', null)
->where('users.is_active', 0)
->whereBetween('websites.publishing_price',[ '15', '20'])
->take(25);
You can make the Union of your data by taking out separately by query first 7 websites and merge it second query with your 18 websites.
Short example:
$seven = DB::table('websites')
...
->whereBetween('websites.publishing_price',[ '20', '25'])
->take(7);
$result = DB::table('websites')
...
where('websites.publishing_price', '<=', 25)
->limit(18)
->unionAll($seven)
->get();

Select Price field MySQL JSON on Laravel

I want to get data that Price is greater than or equal to a specified value (taken from the input).
$minPrice = $request->min_price;
$maxPrice = $request->max_price;
$value = Dproduct::where(['status' => 1])->where('price', '>', $minPrice)->get();
But the Price is JSON in database, I can't get it. Currencies such as: VND, USD, TWD,...
All answers are respected!
Thanks so much!
if you are using laravel 5.7 or greater then you may be able to select within the JSON. See the docs here for more details.
Note: for this to work you must use json data type for your field in database.
$minPrice = $request->min_price;
$maxPrice = $request->max_price;
$value = Dproduct::where(['status' => 1])->where('price->USD', $minPrice)->get();

server-side rendering mysql limit n rows and paginate

I am using server-side rendering in DataTable.
I have a variable that determines limit to number of rows from database.
I am trying to fetch, say, 100 rows, and from DataTable with pagelength of 25, paginate it upto 4 pages.
Also, if the limit variable is 4 or 10, or anything less than pagelength value, then all records will be displayed in a single page.
Here's my code:
#get datatable params
$draw = $this->request->input('draw');
$start = $this->request->input('start');
$dt_limit = $this->request->input('length'); // datatable pagination limit
$limit_rows = $this->request->input('limit');
# query
$result_product_urls = DB::table('product_match_unmatches')
->select('r_product_url', 'r_image_url_main')
->selectRaw('count(distinct s_product_url, r_product_url) as frequency,
GROUP_CONCAT(CONCAT(s_image_url, "&s_product_url=", s_product_url) SEPARATOR " | ") as source_products')
->groupBy('r_product_url')
->where('request_id', '=', $reqId)
->orderBy('frequency', 'DESC')
->take($limit_rows);
$recordsTotal = $result_product_urls->get()->count();
$urls = $result_product_urls->offset($start)->limit($dt_limit)->get();
This will always fetch 25 rows from the database, since the dataTable page-length is 25.
But I need to limit the rows based on $limit_rows value, and not $dt_limit.
If I only do $urls = $result_product_urls->get();, then if $limit_rows value is 100, all 100 rows are displayed in the same page.
How can I fetch limit rows from database, and then paginate through it?
I hope I make my post clear.
I'll take a stab at this, but it's not entirely clear to me the exact thing you are attempting to accomplish based on the code sample.
According to Laravel docs take and limit appear to be equivalent.
https://laravel.com/docs/5.8/queries#ordering-grouping-limit-and-offset (bottom of this section)
What it looks like the code is doing:
Using $limit_rows value with ->take() method in the $result_product_urls query builder object:
# query
$result_product_urls = DB::table('product_match_unmatches')
->select('r_product_url', 'r_image_url_main')
->selectRaw('count(distinct s_product_url, r_product_url) as frequency,
GROUP_CONCAT(CONCAT(s_image_url, "&s_product_url=", s_product_url) SEPARATOR " | ") as source_products')
->groupBy('r_product_url')
->where('request_id', '=', $reqId)
->orderBy('frequency', 'DESC')
->take($limit_rows); /* <------------- limit_rows HERE */
But then also using $dt_limit value with ->limit() method when setting the $urls variable:
$recordsTotal = $result_product_urls->get()->count();
$urls = $result_product_urls->offset($start)->limit($dt_limit)->get();/*<-- dt_limit HERE */
If you don't want to use $dt_limit as a limit then don't use it...? I think maybe what you are trying to do is have a query with a limit on the result set, and then a sub limit on that? I can't figure out a reason to want to do that, so I might be missing something. I don't think you can use ->take() and ->limit() on the same query.
Shouldn't this accomplish your goal?:
# query
$result_product_urls = DB::table('product_match_unmatches')
->select('r_product_url', 'r_image_url_main')
->selectRaw('count(distinct s_product_url, r_product_url) as frequency,
GROUP_CONCAT(CONCAT(s_image_url, "&s_product_url=", s_product_url) SEPARATOR " | ") as source_products')
->groupBy('r_product_url')
->where('request_id', '=', $reqId)
->orderBy('frequency', 'DESC');
/* ->take($limit_rows); remove this */
$recordsTotal = $result_product_urls->get()->count();
$urls = $result_product_urls->offset($start)
->limit($limit_rows) /* set limit to $limit_rows */
->get();
If not, then maybe you can clarify.
use offset alongwith limit i.e.
$users = DB::table('users')->skip(10)->take(5)->get();
or
$users = DB::table('users')->offset(10)->limit(5)->get();

Test JSON data from database and get the column

I have in my database a column which store a json and I would like to recover the value of a certain object of my json in order to test it
So my column "JSON" contains that
{
"type":"index",
"data ":{"index":2}
}
And if i receive 2, i need to get this column which contain the index 2 to delete it
I have tried this:
$column = Table::where('JSON["data"]["index"]','=', '2' )
->first();
Table::dropColumn($column);
But it doesn't work, beacause i can't get the index
If you are using latest laravel version then,
$column = Table::where('JSON->data->index','2')->first();
Should work.
You can refer official laravel documentation for json where clause here.
Simply use SQL Like
->where('JSON', 'like', '%"index": "2"%');
Since you gave JSON value as a string, it was unable to get the index value.
Can you please try like below,
$column = Table::whereRaw(JSON["data"]["index"], '=', '2' )
->first();
Table::dropColumn($column);

CodeIgniter Where_In select from different table?

i am trying to covert this query in active record
SELECT
crm_clients.id,
crm_clients.`moved_date`,
crm_clients.`contractor_id`
FROM
dev_pfands.`crm_clients`
WHERE crm_clients.`contractor_id` = 11
AND (
crm_clients.`status` = 9
OR crm_clients.`status` = 8
OR crm_clients.`status` = 7
)
AND crm_clients.id IN
(SELECT
crm_client_cheques.`client_id`
FROM
dev_pfands.`crm_client_cheques`)
AND crm_clients.`moved_date` BETWEEN '2014-08-01'
AND '2014-11-29 '
AND crm_clients.`contractor_id`<>''
GROUP BY crm_clients.`id
the section I'm having issue is
AND crm_clients.id IN
(SELECT
crm_client_cheques.client_id
FROM
dev_pfands.crm_client_cheques) `
i've tried the where_in method but overtime i try to include my attempt of $this ->db_pfands -> where('crm_client_cheques.client id' ,'id'); get hit with errors and have no idea how to get past this.
the original query should return 703 rows and when I've removed the part I'm stuck with it increase to 3045 so i need it to be included. any help is appreciated.
First of all you have a error in your code.
$this->db_pfands->where('crm_client_cheques.client id', 'id');
This will be
$this->db_pfands->where('crm_client_cheques.client_id', 'id');
You have to provide the right column name and as far i know database's column name have not contain any space.
Now I think this active record query will help you to get your result.
$query = $this->db->select('crm_clients.id, crm_clients.moved_date, crm_clients.contractor_id')
->where('moved_date BETWEEN "2014-08-01" AND "2014-11-29"')
->where('contractor_id', 'id')
->where_in('status', [9,8,7])
->from('crm_clients')
->join('crm_client_cheques', 'crm_client_cheques.client_id = crm_clients.id')
->group_by('id')
->get();
$result = $query->result();
May be you have change couple of names because they are in different database, but i believe you can do it.

Categories