I dont understand where goes wrong. When I add this
where('units.solddate','>=','DATE_SUB(CURDATE(), INTERVAL 30 DAY)')
where clause and my result is empty. I tried in phpMyadmin and it does return results.
$query= (tables)
->select(DB::raw('SUM(units.price) as price, DATE(units.solddate) as date, DAY(units.solddate) as day'))
->where('units.solddate','>=','DATE_SUB(CURDATE(), INTERVAL 30 DAY)')
->where('units.solddate','<=','NOW()')
->groupBy('date')
->get();
Please advice.
The reason why the constraints don't work is that Eloquent takes the value you compare with literally, escapes it when needed and then uses in a query. So if you do
->where('units.solddate','<=','NOW()')
you're in fact comparing units.solddate with a strin NOW(), like in:
... WHERE units.solddate <= 'NOW()'
If you want to use MySQL functions in your query you have to explicitely tell Eloquent/QueryBuilder that you mean the raw value that you provided by using DB::raw() to wrap the value.
The following should work for you:
->where('units.solddate','>=',DB::raw('DATE_SUB(CURDATE(), INTERVAL 30 DAY)'))
->where('units.solddate','<=',DB::raw('NOW()'))
Related
Hi I got stack when i want to show data using interval in Laravel, I have this code and it's running well on Mysql and showing what i want. but how to implement the mysql code to laravel ?
this is mySql code
SELECT * FROM projects WHERE end_date BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY)
and i have trying some ways on Laravel Controller but array is null
$highlightProject = project::select('*')->where(DB::raw('end_date BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY)'))->get();
dd($highlightProject);
The reason you're not getting the results you want is because you're using where instead of whereRaw. In this case your query going to return:
select * from `projects`
where end_date BETWEEN
CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY) is null
(notice the is null part).
To get the results you want change where to whereRaw (you can remove the DB::raw):
project::whereRaw('end_date BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY)')->get();
Alternatively, you could use a mixture of whereBetween and Carbon:
project::whereBetween('end_date', [now(), now()->addDays(30)])->get();
Check out this answer for more information.
This may not be the solution you would have preferred, (I do not know why your current query would not work and as #tadman suggested, I too suggest checking the produced query), but an alternative approach would be to try with query builder methods and Carbon date library that is shipped with Laravel.
$highlightProject = Project::whereBetween('end_date', [\Carbon\Carbon::today(), \Carbon\Carbon::today()->addDays(30)])->get();
Try with whereRaw() sometime where() not properly work DB::raw()
$highlightProject = project::select('*')->whereRaw(DB::raw('end_date BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 30 DAY)'))->get();
I want to filter some items based on two different dates using MySQL. In my database I store data like 2017-03-28 10:55:10. But I need only the date part, not the time so I used the DATE() function:
select sum(cashamount) as sumcashsalesamount,
DATE(transactiondate) as datepart
from master_transaction
where transactiondate BETWEEN '2017-02-22%' AND '2017-03-28%'
order by transactiondate desc
Above this query have two dates 2017-02-22% and 2017-03-28% but this return no result.
But when I change this 2017-03-28% date to 2017-03-29% (tomorrow date) I get results.
Don't use between with "dates". I put that in quotes, because your values are really datetime values.
The best way to write this condition is:
where transactiondate >= '2017-02-22' and
transactiondate < '2017-03-29'
Note the inequality for the second condition. BETWEEN is inclusive, so it would include midnight on 2017-03-28.
Why is this best?
It allows the query optimizer to take advantage of indexes and partitions.
It is exactly the logic that you want.
It works for both date and datetime types.
BETWEEN is inclusive on both sides, and if no time component is given for a date, it defaults to 00:00:00. Since 2017-03-28 10:55:10 > 2017-03-28 00:00:00 it is not included in the result set.
2017-03-28% = 2017-03-28 00:00:00
If something happened during that day, you need 2017-03-28 23:59:59, or date_sub(2017-03-29, INTERVAL 1 second) for ease
You can only use wildcard characters (%) with LIKE.
Use:
where date(transactiondate) BETWEEN '2017-02-22' AND '2017-03-28'
if you use between and you want today, all day, you must put tomorrow date
And i fix my problem
select sum(cashamount) as sumcashsalesamount
from master_transaction
where DATE(transactiondate)BETWEEN '2017-02-22' AND '2017-03-28'
order by transactiondate desc
I just re-place the DATE(transactiondate) in where condition its worked
Although I have been working with PHP for a while, the one part of it I am still trying to get right is time.
I am creating a simple script that will check if the timestamp is greater than or equal to an hour, and if it is, it will be deleted from the database.
2013-01-03 20:30:25
DELETE FROM tablename WHERE timestamp = ?????
I am not sure how to execute the query to delete values with a timestamp of over an hour from the current time. Any help is greatly appreciated.
DELETE FROM tablename WHERE `timestmap` < DATE_SUB(NOW(), INTERVAL 1 HOUR)
Ref:- date_add and date_sub
First of all, 2013-01-03 20:30:25 is not a timestamp, it is a formatted date. The timestamp for that date would look like this: 1357245025. You can convert it to a timestamp using the strtotime function. You can also work out the timestamp of an hour ago by using strtotime("-1 hour") and performing a comparison on the values.
It might be faster just to do all of this within the MySQL query though, MySQL provides queries to do this, using a query similar to the one that Amit Garg provided.
I have a date, say its called $date. I want a a mysql_query to search a select number of weeks,days or even months before my $date. Is this possible? My explanation is not the greatest, but I do need a answer for this and do not know how to properly question it.
You could use mysql interval function?
"select * from table where `date` BETWEEN DATE_SUB(".$date.",INTERVAL 15 DAY ) AND CURDATE( )
That'll return the records from the last 15 days, you could use = insted of between if you want the records exactly 15 days old, or modify it for days, months, etc.
edit: if your working with php's time() remeber to use FROM_UNIXTIME($phpdate) inside your query.
i have a solution for this in SQL, Take it, if it would helps you
Day($date) gives you the date in the vaariable
Month($date) gives you the Month in the vaariable
Year($date) gives you the year in the vaariable
using simple where conditions, now you can search for a particulars
You can use the DATE_ADD and DATE_SUB functions to modify a date, and mysql understands a BETWEEN clause using dates. However, you can also use the TIMESTAMPDIFF function like so:
"SELECT foo FROM table WHERE TIMESTAMPDIFF(DAY, dateField, '$date') < '$desired_days'"
I need to delete rows where a datetime field is over 2 weeks old.
This is what I have came up with
$duration = Date::WEEK * 2; // int(1209600)
$query = 'DELETE FROM properties
WHERE TIMEDIFF(' . date(DATE_ISO8601) . ', reserved_datetime) > ' . $duration;
I don't often write complicated queries (preferring to do stuff in PHP, where I'm more comfortable) but I'd like to know more about them, plus doing this sort of thing in PHP would be very inefficient and I am handling a large amount of rows.
Anyone know what I'm doing wrong? Cheers.
Update
I gave Wallyk's answer a shot, changing it slightly in phpMyAdmin to SELECT just so I could see what was going on.
This is what I used
SELECT *
FROM properties
WHERE date_sub( `reserved_datetime` , INTERVAL 2 week ) >0
LIMIT 0 , 30
The only problem however, is that it has returned rows where the reserved_datetime is 2010-02-28 10:45:59, definitely less than 2 weeks ago (from now).
I thought of checking MySQL's internal date. I have been using date(DATE_ISO8601) in my queries, because MySQL's NOW() wasn't exactly right (it just returned if interested 2010-02-28 20:09:19).
Is there a way to specify the current date in that query? Any other suggestions?
Many thanks
Another Update
Here is a screenshot from phpMyAdmin that may demonstrate anything better than my words can. Oh, and the reason it has returned 3 only is because all the others have blank values, i.e. 0000-00-00 00:00:00
wallyk's answer is not correct. Think about what you're doing - subtracting two weeks from almost any date will still be greater than zero (zero = 1/1/1970). I think you want something more like this:
DELETE FROM properties WHERE DATE_SUB(NOW(), INTERVAL 2 WEEK) > reserved_datetime
Use:
FROM PROPERTIES p
WHERE p.reserved_datetime <= DATE_SUB(NOW(), INTERVAL 2 WEEK)
Mind that because of using NOW(), the two week old date will include the time portion.
I don't have a mysql database so I can't say if it works for sure, but it does in postgresql:
DELETE FROM properties WHERE (NOW() - reserved_datetime < interval '2 weeks')
Try this instead:
$query = 'DELETE FROM properties
WHERE date_sub(reserved_datetime, interval 2 week) > 0';
This assumes that reserved_datetime is the field name in the table.
(Tested with MySQL 5.0.46-standard.)