How to delete records using ActiveRecord with mySQL function as WHERE clause

I have a table called ChatSessions where I track active users in the chat. I need to cancel expired user sessions from a table every 10 minutes. Using pure php-mysql is simple, but I have absolutely no idea how to convert it to ActiveRecord in CodeIgniter. A simple SQL query below:

SELECT *
FROM `ChatSessions`
WHERE `SessionExpires` < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )

Can someone tell me the equivalent code in CodeIgniter using ActiveRecord?

+3
source share
2 answers

The following code should do this:

// You can use custom strings in the where() function
$where = "SessionExpires < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
// although you may need to set the third parameter to FALSE in order to stop CI from protecting your fields.
$this->db->where($where, null, false);
$this->db->delete('ChatSessions');

You can also try the following (but I don't know if this will work):

$where_condition = "DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
$this->db->where("SessionExpires <", $where_condition, false);
$this->db->delete('ChatSessions');
+4
source

ActiveRecord, SQL, . SQL .

$sql = "DELETE FROM ChatSessions 
        WHERE SessionExpires < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
$this->db->query($sql);
+2

Source: https://habr.com/ru/post/1748902/


All Articles