Delete using active record - activerecord

How to achieve below query in ActiveRecord ?
"delete from model where date(created_at)=#{some_date}"
where created_at is sql datetime field.
One option I can think is calculate
start_date = starting time of the day
end_date = end time of the day
and
Model.delete_all('created_at' >= start_date, 'created_at' < end_date)
Any other clean option ?

Assuming database you are using is MySql and start_date is a date object.
Use mysql DATE_FORMAT function
Model.delete_all("DATE_FORMAT(created_at, '%Y-%m-%d') >= ?",
start_date.strftime("%Y-%m-%d"))

Related

How can i show single data in view if today date is in between start date & end date in laravel?

I have Admission table which have id, school_id, start_date,end_date etc and i want to show single data if today's date is between start_date & end_Date in laravel eloquent
Applying below code you can get the latest data of current date
$currentDate = date('Y-m-d');
$result = my_table::where(DB::raw('DATE(start_date)'), '<=' , $currentDate)
->where(DB::raw('DATE(end_Date)'), '>' , $currentDate)
->orderBy('id','desc')
->first();
`$start_date = date('2018-01-01');
$end_date = date('2018-05-02');
Adminssion::whereBetween(Carbon\Carbon::now()->toDateString(), [$start_date, $end_date])->get();`
The carbon now() function will give you current date and time. And toDateString() function only give you today date. And with whereBetween() function you can compare the current date between start_date and end_date.

Laravel eloquent possible bug?

I want to join two tables and filter on a field in the joined table. I don't think the actual tables matter in this question, but it's a table with dates joined with a table with the event info, so there are more dates possible for 1 event.
I made this eloquent line:
Event_date::whereRaw('startdate >= curdate() OR enddate >= curdate()')->whereHas('Event', function($q){$q->where("approved",true );})->orderBy('startdate', 'asc')->orderBy('enddate', 'asc')->toSql());
the filter doesn't work though. So thats why i added the ->toSql() to the line.
I get the following back:
select * from `event_dates` where startdate >= curdate() OR enddate >= curdate() and exists (select * from `events` where `event_dates`.`event_id` = `events`.`id` and `approved` = ?) order by `startdate` asc, `enddate` asc
You see that the 'where("approved",true )' results in 'where ..... and and approved = ?)' Where does the questionmark come from??? I tried diferent things, like '1', 1, 'True', True, true, 'true'...everything comes back as a questionmark.
Any suggestions??
Thanks!
Erwin
This is expected behaviour. Laravel uses prepared statements. To get parameters that are put into placeholders, you can use
$query->getBindings();
so for example in your case you can use:
$query = Event_date::whereRaw('startdate >= curdate() OR enddate >= curdate()')->whereHas('Event', function($q){$q->where("approved",true );})->orderBy('startdate', 'asc')->orderBy('enddate', 'asc'));
and now
echo $query->toSql();
var_dump($query->getBindings());
to get both query with placeholders and values that will be put in place of placeholders.

Ruby format DateTimeParameter in where query

I want to do a query like this:
bookings = Booking.where(user_id: #current_user.id, start_at: date.to_datetime)
The problem in this case is, that I just get results in bookings which match a timestamp 00:00:00 which is quite logical.
Is there a possibility to format the start_at parameter in the query to date, so that I just compare two dates and not datetimes?
Try convert your datetime field to date via SQL:
bookings = Booking.where(user_id: #current_user.id)
.where("DATE(start_at) = ?", date)
DATE() extracts the date part of a datetime expression.
Note: it does not works in PotsgreSQL
Or:
bookings = Booking.where(user_id: #current_user.id,
created_at: date.beginning_of_day..date.end_of_day)
How about this?
bookings = Booking.where(user_id: #current_user.id, start_at: start_date..end_date)
or
bookings = Booking.where(user_id: #current_user.id)
.where('start_at > ? AND start_at < ?', start_date, end_date)
where start_date and end_date are the two dates you wish to check between.

Rails 4: column reference "updated_at" is ambiguous with Postgres

I am trying to query the database with a DateTime range for the 'updated_at' field. The front end sends queries in a JSON array:
["2015-09-01 00:00:00","2015-10-02 23:00:00"]
At the Rails controller, I parse the two strings to DateTime using:
start_date = DateTime.parse(params[:date_range_arr][0])
end_date = DateTime.parse(params[:date_range_arr][1])
#...
#events = #events.where('updated_at BETWEEN ? AND ?,
start_date, end_date
)
The queries show:
WHERE (updated_at BETWEEN '2015-09-01 00:00:00.000000' AND '2015-10-02 23:00:00.000000')
And the errors are:
ActionView::Template::Error (PG::AmbiguousColumn: ERROR: column reference "updated_at" is ambiguous
LINE 1: ...texts"."id" = "events"."context_id" WHERE (updated_at...
Do you have by any chance a default scope with a join or an include on the Event model or in the code above what's included in the original question?
Either way, you simply need to be more specific with your query as follow:
#...
#events = #events.where('events.updated_at BETWEEN ? AND ?,
start_date, end_date
)

Operation with dates in Grocery CRUD and Codeigniter

In table Employees I have columns: start_date(dd/mm/yyyy), end_date(dd/mm/yyyy) and period(dd/mm/yyyy).
I want to put calculation in column period = end_date - start_date.
I don't now haw to take data from columns start_date and end_date and write operation for column period. Please help me to solve my problem.
This is an SQL question IMO. But you tagged it as codeigniter so I guess you need CI code to go with this.
Anyway you can use DATEDIFF on your query. Like so.
$sql = "SELECT DATEDIFF(start_date,end_date) AS DiffDate";
Then fire it up on CI using query().
$qry = $this->db->query($sql);
return $qry->result();

Resources