Score:0

Condition that deletes rows older than 30 days

at flag

How can I query a condition that deletes the rows with column Date older than the last 30 days in DBTNG format?

I have tried this, but it's wrong.

$connection = \Drupal::database();
$connection->delete('my_table')
    ->condition('Date', now() . ' - INTERVAL 30 day', '>');
$connection->execute();

Screenshot of table with nid and Date columns

Hodba Khalaf avatar
eg flag
Is it a created date? you try using EntityTypeManager to query the condition, then loop and delete them one by one. I would do it using a batch approach.
id flag
PHP’s now() function (a deprecated alias for time()), which that code calls, returns the current Unix timestamp. You can’t subtract “INTERVAL 30 day” from it.
Score:1
at flag

Considering that the field Date is type date and has values with the following format: Y-m-d (2023-04-04).

// Returns a timestamp equivalent to: 2023-07-01 17:20:53 UTC (today is 2023-07-31)
$range = strtotime('now -30 days'); 

// Converts the previous timestamp to Y-m-d format
$rangeTimestamp = date('Y-m-d', $range); 

// Stores the database service into a variable
$connection = \Drupal::database();
        
// Query that retrieves rows with column Date (Y-m-d) with a value older than specific range. 
$query =  $connection->delete('my_table')
          ->condition('Date', $rangeTimestamp, '<=')
          ->execute();

// If Date is greater or equal '>=', it's inside the range of 30 days.
// If Date is lower or equal '<=', it's outside the range, and is older than 30 days.
apaderno avatar
us flag
Actually, `$range` contains a timestamp and `$rangeTimestamp` contains a date string. The first variable should be really named `$rangeTimestamp`, and the second variable should be named `$range`. Actually, they are not ranges, so their names should not contain *range*.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.