Laravel - select row between start date and end date using eloquent - php

I want to convert this query into laravel eloquent,
select * from schedule where (now() between start_date and end_date);
I tried using whereBetween, but I got some error.
$schedule = Schedule::whereBetween(Carbon::now(), ['start_date', 'end_date'])->get();
the error looks like this
QueryException in Connection.php line 647:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '2017-06-01 06:17:30' in 'where clause' (SQL: select * from schedule where 2017-06-01 06:17:30 between start_date and end_date)
any idea?

$from = $request->from;
$to = $request->to;
$title="Sales From: ".$from." To: ".$to;
$sales = Sale::whereBetween('created_at', [$from.' 00:00:00',$to.' 23:59:59'])->get();

$schedule = Schedule::where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
->get();
Or
$schedule = Schedule::whereRaw('(now() between start_date and end_date)')->get();

The whereBetween is used only when you want to find a row where a single column is between 2 values, what you want to do is :
$now = Carbon::now();
$schedule = Schedule::where('start_date', '<=', $now)
->where('end_date', '>=', $now)
->get();

whereBetween should used like this, ->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172)) whose first parameter is the column name, and the second is the region.
In you situation you can use ->where('start_date', '<' Carbon::now())->where('end_date', '>' Carbon::now());

You can use whereBetween('date_field',[$from_date, $to_date]) to fetch the data between two dates but it should be in the array format.
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->get();
return response()->json($products);
You can also use whereBetween(whereBetween('date_field',[$from_date, $to_date])) with multiple where conditions like:
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->where(function ($query) use ($search) {
$query->where('employee_id', 'like', '%'.$search.'%')
->orWhere('employee_name', 'like', '%'.$search.'%');
})
->get();
return response()->json($products);
I hope this will work for you :)

Related

How to transform sql query into Query Builder Laravel way?

I need to convert this query into Laravel query builder or ORM
SET #start_date = '2020-11-01';
SET #end_date = '2020-11-08';
SET #duration = CONVERT(#end_date, DATE) - CONVERT(#start_date, DATE);
SELECT item_id, days
FROM (
SELECT item_id, sum(end_date - start_date) AS days
FROM schedule WHERE start_date >= #start_date AND end_date <= #end_date
GROUP BY item_id) AS virtual
WHERE days = #duration;
(i use Laravel 8)
i could not find similar example I could analize and try by myself :(
i try this :
$res = DB::table('schedule')
->select('schedule.item_id' , DB::raw("SUM(schedule.end_date - schedule.start_date) as days"))
->where('start_date', '>=', $start_date)
->where('end_date', '<=', $end_date)
->groupBy('item_id')
->where('days', '=', $duration)
->get();
but i get error :
Column not found: 1054 Unknown column 'days' in 'where clause'
ok i know what is wrong
i tried to access 'days' column before it is created with AS
that column will be available after line ->get() is executed.
So I changed order of these 2 lines :
->where('days', '=', $duration)
->get();
to
->get()
->where('days', '=', $duration);
and now works :)

Laravel multiple WHERE clauses

I have a requirement to add multiple where clauses to a Laravel SQL query.
So far my PHP code has been:
date_default_timezone_set('America/Los_Angeles');
$today = getdate();
$year = $today['year'];
$month = $today['mon'];
$day = $today['mday'];
$today_ = $day.'-'.$month.'-'.$year;
$result = DB::table('task')
->select('*')
->where(
['rowstate', '<>', 'Ready'],
['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
->get();
But above code returns:
Column not found: 1054 Unknown column '0' in 'where clause'
(SQL: select * from `task_tab` where (`0` = rowstate and `1` = <> and `2` = Ready))
I want to generate below SQl statement:
SELET *
FROM task
WHERE rowstate <> 'Ready'
AND DATE_FORMAT(due_date, "%d-%m-%y") < $today
You have 2 possible solutions.
Instead of:
->where(['rowstate', '<>', 'Ready'], ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
you can use
->where('rowstate','<>','Ready')->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y"','<', $today_);
or
you can use array syntax like this:
->where([
['rowstate', '<>', 'Ready'],
[DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_]
]);
So to sum up you were missing enclosing your data into outer array, and you need to use DB::raw in case you don't use raw column names
You can't use sql function's directly in laravel where class. You need to use DB::raw() for same.
So your query will be like :
$result = DB::table('task')
->select('*')
->where('rowstate', '<>', 'Ready')
->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_)
->get();
Try this
->where([
// ^
['rowstate', '<>', 'Ready'],
['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_]])
// ^

Laravel 4.2 - Select only rows where count of rows based on another query are 0

I want to set up scheduled emails for recommended oil changes. To do this, I need to select from a table of line items where the last oil change was over 3 months ago. I need a condition to ignore currently selected customer rows where an oil change was purchased under 3 months ago. How would I add this condition?
$search_term = 'oil change';
$date = new DateTime('-3 months');
$users = $this->prospectInstance->getDatabase()->table('LineItems')
->join('WorkOrder', 'WorkOrder.id', '=', 'LineItems.order_id')
->join('Customer', 'Customer.customer_id', '=', 'WorkOrder.customer_id')
->where('LineItems.line_type', 'like', "%$search_term%")
->where('WorkOrder.create_date', '<=', $date)
// this block produces errors
->whereNotIn('Customer.customer_id', function($query) use ($search_term, $date)
{
return $query->where('LineItems.line_type', 'like', "%$search_term%")
->join('WorkOrder', 'WorkOrder.id', '=', 'LineItems.order_id')
->join('Customer', 'Customer.customer_id', '=', 'WorkOrder.customer_id')
->where('WorkOrder.create_date', '>=', $date);
})
->orderBy('WorkOrder.create_date', 'DESC')
->groupBy('Customer.customer_id');
Table Structure:
LineItems
order_id
line_type
WorkOrder
id
customer_id
create_date
Customer
customer_id
Edit: I was able to use the advice below to use two separate queries to accomplish this, but I'd like to know if there is a single query I can create to accomplish the same result:
$search_term = 'oil change';
$date = new DateTime('-3 months');
$base_query = $this->prospectInstance->getDatabase()->table('LineItems')
->join('WorkOrder', 'WorkOrder.id', '=', 'LineItems.order_id')
->join('Customer', 'Customer.customer_id', '=', 'WorkOrder.customer_id')
->where('LineItems.line_type', 'like', "%$search_term%")
->orderBy('WorkOrder.create_date', 'desc')
->groupBy('Customer.customer_id');
$recent = clone $base_query;
$users = clone $base_query;
$recent->where('WorkOrder.create_date', '>', $date)
->select('Customer.customer_id');
$users->where('WorkOrder.create_date', '<=', $date)
->whereNotIn('Customer.customer_id', $recent->lists('customer_id'));
I think this would work but is obviously not tested:
$users = $this->prospectInstance->getDatabase()->table('Customer')
->join('WorkOrder', 'WorkOrder.customer_id', '=', 'Customer.customer_id')
->join('LineItems', 'LineItems.order_id', '=', 'WorkOrder.id')
->where('LineItems.line_type', 'like', "%$search_term%")
->whereNotIn('Customer.customer_id', function($query) use ($date, $search_term)
{
$query->select('Customer.customer_id')
->from('Customer')
->join('WorkOrder', 'Customer.customer_id', '=', 'WorkOrder.customer_id')
->join('LineItems', 'WorkOrder.id', '=', 'LineItems.order_id')
->where('WorkOrder.create_date', '>', $date)
->where('LineItems.line_type', 'like', "%$search_term%");
})
->orderBy('WorkOrder.create_date', 'desc')
->groupBy('Customer.customer_id');

Laravel query - getting objects and their counts from related table

I have table articles and it's related tables comments, views and likes which have a field article_id and in my function I am sending name of the related table, with $request['option'], comments for example, with ajax, to get the top 5 most commented articles. But in my function I am getting from the query result with article_ids and counts and then I am iterating through the results with foreach loop and getting article object with article_id that I am sending in the query. I would like to avoid doing that query for each of the results from the first query. What would be the way to do it more elegantly and without so many calls to DB?
This is my code:
public function mostArticle(Request $request) {
$from = $request['from'];
$to = $request['to'];
$result = DB::table($request['option'])
->select(DB::raw('article_id'), DB::raw('count(*) as count'))
->whereDate('created_at', '>=', date($from).' 00:00:00')
->whereDate('created_at', '<=', date($to).' 00:00:00')
->groupBy('article_id')
->orderBy('count', 'DESC')
->take(5)
->get();
foreach($result as $val){
$article = Article::where('id', $val->article_id)->first();
$mostSomethingArticle[$article->id] = [];
$mostSomethingArticle[$article->id]['title'] = $article->title;
$mostSomethingArticle[$article->id]['summary'] = $article->summary;
$mostSomethingArticle[$article->id]['count'] = $val->count;
}
return json_encode($mostSomethingArticle);
}
You can use relations or joins. But im not sure, if this code is correct:
$result = DB::table($request['option'])
->select('article.id', 'article.title', 'article.summary', DB::raw('count('.$request["option"].'.id) as count'))
->join('article', 'article.id', '=', $request['option']."article_id")
->whereDate('created_at', '>=', date($from).' 00:00:00')
->whereDate('created_at', '<=', date($to).' 00:00:00')
->groupBy('article_id')
->orderBy('count', 'DESC')
->take(5)
->get();
return $result;

Find By Date Laravel 5.2

I have some problem with searching by existing date.
In Model:
$date = '2016-01-14';
public static function getByDate($date)
{
$query = self::select('date', DB::raw('SUM(test_count) as test'))
->whereDate('date', '=', $date)
->groupBy('date')
->orderBy('date', 'ASC')
->get();
}
But I didn't get a result, because this code creates SQL:
select `date`, SUM(test_count) as test from `test_table` where date(`date`) = 2016-01-14 group by `date` order by `date` asc limit 1
Not quoted around of date => 2016-01-14
How to fix it?
I try to use whereRaw with params, for example:
return $query->whereRaw("date= ?",[$date]);
but it did not help...
You need to change the ->whereDate('date', '=', $date) to this:
->where('date', '=', $date)
Or you can use this:
->whereDate($date)
So, it's obvious that, you can use either ->whereDate($date) or ->where('date', '=', $date) because whereDate is a dynamic method and in this case, it'll become: where('date', '=', $date).

Categories