Find a date older than 15 days in laravel - mysql

i need to show compare a delivery date if it is 15 days over and also show a track_track_status=0 as default.when i do this it throws the error
Error
Column not found: 1054 Unknown column ''delivery_date' + INTERVAL 15 DAY < NOW()' in 'where clause
$secondstatus = DB::table('registrations')
->join('ssi_tracks', 'registrations.registration_id', '=', 'ssi_tracks.registration_id')
->select('ssi_tracks.ssi_track_id', 'address', 'model', 'chassis', 'delivery_date','ssi_tracks.track_second_status')
->where([["ssi_tracks.track_second_status", "=", 0]])
->orWhereRaw('registrations.delivery_date + INTERVAL 15 DAY <= NOW()')
->get();

Use Carbon with laravel orWhere instead
->orWhere( 'delivery_date', '<=', Carbon::now()->subDays(15))

use raw query as below:
$now = \Carbon\Carbon::now();
->orWhere(DB::raw(registrations.delivery_date + INTERVAL 15 DAY, "<=", $now))
check it and response here if it returns any error.

Just do:
$secondstatus = DB::table('registrations')
->join('ssi_tracks', 'registrations.registration_id', '=', 'ssi_tracks.registration_id')
->select('ssi_tracks.ssi_track_id', 'address', 'model', 'chassis', 'delivery_date','ssi_tracks.track_second_status')
->where([["ssi_tracks.track_second_status", "=", 0]])
->orWhere('registrations.delivery_date', '<=', \DB::raw("NOW() - INTERVAL 15 DAYS")))
->get();
Problem being that the query builder will alias the table name and will but will not alias it if it's within a whereRaw

Related

How to write the below eloquent query code using raw query in laravel?

My eloquent query:
$data = (new Model())->whereDate('start_date', '<=', Carbon::today())
->whereDate('end_date', '>=', Carbon::today())
->count();
The raw query I have tried:
$data = (new Model())->select(DB::raw("COUNT(id) as countData where date(start_date) <= NOW() and date(end_date) >= NOW()"))->get();
How can I write my eloquent query as raw query. The below raw query gives me syntax violation error;
This is because of how you are constructing your query. If you inspect the generated SQL statement you'll see that the SQL FROM clause is actually on the end of your statement and not at all where it should be.
You'll want to split your WHERE clauses out and use either where or whereRaw. For example:
$data = (new Model)->select(DB::raw('COUNT(id) as countData'))
->whereRaw('date("start_date") <= NOW() AND date("end_date") >= NOW()')
->get();
Your question was a little unclear but if you want to do what you did with eloquent in raw query, be noted that the select function of DB in raw by itself, so simply write your query inside select function:
$tableName = (new Model)->getTable();
$data = DB::select("
SELECT COUNT(`id`) as `countData` FROM `$tableName`
WHERE DATE(`start_date`) <= NOW() AND DATE(`end_date`) >= NOW()
")->first();
Alternatively you may use whereRaw function of your Model:
$data = Model::whereRaw(
"DATE(`start_date`) <= NOW() AND DATE(end_date) >= NOW()"
)->count();

Date between two values - Lavarel SQL

I have a structure table like this : Start_date End_date
Now with today's date, I should go and get all the data including from Start_Date and End_Date, what can I do?
I tried with
SELECT *
FROM text
WHERE Start_date BETWEEN '2021-10-10' AND '2021-10-08'
OR End_date BETWEEN '2021-10-08' AND '2021-10-10
but to no avail ...
The whereBetween method in Laravel will determine if an items value is between the given range.
$start = '2021-10-08';
$end = '2021-10-10';
Text::whereBetween('start_date', [$start, $end])
->whereBetween('end_date', [$start, $end])
->get();
if you just want to get data from start to end date you can use this eloquent Code
$start_date = "2020-10-20";
$end_date = "2021-10-20";
Text::where(function ($wh) use ($start_date, $end_date) {
$wh->whereBetween('Start_date', [$start_date, $end_date])->orwhereBetween('End_date', [$start_date, $end_date]);
})->get();
here is a raw query from the above eloquent code
select * from `users` where (`Start_date` between '2020-10-20' and '2021-10-20' or `End_date` between '2020-10-20' and '2021-10-20')
if you want to find data from start to end date including today's date you can you this eloquent Code
$start_date = "2020-10-20";
$end_date = "2021-10-20";
Text::where(function ($wh) use ($start_date, $end_date) {
$today_date = date('Y-m-d');
$wh->where(function ($or_where) use ($start_date, $end_date) {
$or_where->whereBetween('Start_date', [$start_date, $end_date])
->orwhereBetween('End_date', [$start_date, $end_date]);
})->orwhereRAW("('{$today_date}' between `Start_date` and `End_date`)");
})->get();
here is a raw query from the above eloquent code
select * from `text` where ((`Start_date` between '2020-10-20' and '2021-10-20' or `End_date` between '2020-10-20' and '2021-10-20') or ('2021-10-09' between `Start_date` and `End_date`))

Whats wrong with my code Laravel Callback function GroupBy Month

Im going to count my pallet_condition 0,1,2,3 and group it by month
but i always got an error like this please help whats wrong with my code.
something wrong with my date_format?
My Error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in group statement is ambiguous (SQL: select count(*) as aggregate from `liip_psrm` inner join `liip_psrm_items` on `liip_psrm`.`id` = `liip_psrm_items`.`psrm_items_id` where date(`liip_psrm_items`.`created_at`) >= 2018-10-09 and date(`liip_psrm_items`.`created_at`) <= 2019-01-31 and `liip_psrm`.`status` = 0 and `liip_psrm`.`customer_id` = 14 and `pallet_condition` = 0 group by WEEK(created_at) order by WEEK(created_at) asc)
My Callback function
$problem_condition_computations = function($condition) use ($psrm_maintenance, $start, $end, $customers){
return DB::table('liip_psrm')
->join('liip_psrm_items', 'liip_psrm.id', '=', 'liip_psrm_items.psrm_items_id')
->whereDate('liip_psrm_items.created_at', '>=', $start)
->whereDate('liip_psrm_items.created_at', '<=', $end)
->select(
DB::raw("DATE_FORMAT(liip_psrm_items.created_at, '%Y-%m-%d') AS dates
"))
->where('liip_psrm.status','=', 0)
->where('liip_psrm.customer_id','=',$customers)
->where('pallet_condition', $condition)
->groupBy('dates')
->count();
};
"dates" field you are using in groupBy is alias name, So it do not identifying it and not working as you are expecting.
Same as you used in Select
DB::raw("DATE_FORMAT(liip_psrm_items.created_at, '%Y-%m-%d') AS dates")
Put it in GroupBy
& It will work.
Hope, It will help, Let me know if you still find difficulties.

Illuminate database query with date_sub

I'm struggling with a query using the Illuminate database query builder.
When I use the query the result is not as I expected.
When using the query from the querylog directly with mysql cli, I get the expected result.
With query builder:
->table('CompanyTools')
->select(
'CompanyTools.toolId',
$db->raw('COUNT(CompanyTools.toolId) as count')
)
->whereYear('CompanyTools.date', '>', 'YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))')
->groupBy('CompanyTools.toolId')
->orderBy('count', 'DESC')
->take(1)
->get();
Result:
Array ( [toolId] => 88 [count] => 55 )
With mysql cli:
select `CompanyTools`.`toolId`, COUNT(CompanyTools.toolId) as count from `CompanyTools`
where year(`CompanyTools`.`date`) > YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
group by `CompanyTools`.`toolId`
order by `count` desc
limit 1
Result:
ToolId: 88
count: 17
If I (in the query builder) replace 'YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))'with 2013 I get:
Array ( [toolId] => 88 [count] => 17 )
Somehow the date_sub get ignored so the result includes all years
I tried with ->whereYear('CompanyTools.date', '>', $db->raw('YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))')) without any luck.
I guess I could use php to calculate the desired year, but I would rather get the query right.
Thx in advance
/ j
UPDATE
Replacing
->whereYear('CompanyTools.date', '>', 'YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))')
with
->where($db->raw('YEAR(CompanyTools.date)'), '>', $db->raw('YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))'))
solves it. Not clever enough to figure out why, but perhaps the whereYear function is supposed to be used diffently
As you already found out using
->where($db->raw('YEAR(CompanyTools.date)'), '>', $db->raw('YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))'))
Or alternatively
->whereRaw('YEAR(CompanyTools.date) > YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))')
solves the problem.
But why is that?
For every "normal" query, Laravel uses bindings. Obviously SQL functions like YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) don't work with bindings.
Normally, you can use DB::raw('YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))') and the Laravel won't use bindings. For example in where() (Expression is the class DB::raw() returns)
if ( ! $value instanceof Expression)
{
$this->addBinding($value, 'where');
}
But the whereYear() function doesn't do such a thing. It uses addDateBasedWhere() and just adds a binding without checking if the value is an instance of Expression
protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')
{
$this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');
$this->addBinding($value, 'where');
return $this;
}
This means the query will use bindings and therefore NOT execute the date calculation at all.

Allowing user input once per minute

I have trouble getting this to work.
The thing is that a user is only allowed to create a comment once per minute. As simple as that....
$checkLastComment = Comment::where('user_id', '=', 1)
->where('created_at', '<', 'CURDATE() + INTERVAL 1 MINUTE')->count();
You should use here rather:
$checkLastComment = Comment::where('user_id', '=', $id)
->where('created_at', '>=', 'DATE_SUB(NOW(), INTERVAL 1 MINUTE)')->first();
if ($checkLastComment) {
// user not allowed to add new comment
}
3 issues in your code:
You need greater than >, not less than < operator
You need raw condition
You can't use curdate() since it's time part is 00:00:00 always.
So here's what you want:
$notAllowedToComment = Comment::where('user_id', '=', 1)
->where('created_at', '>', DB::raw('now() - INTERVAL 1 MINUTE'))->count();