Search code examples
phpmysqlpropel

Reset MySQL datetime values with Propel


I want to reset a record's date-time value with Propel in a MySql datetime column to its default value 0000-00-00 00:00:00. This is how I've tried it.

$zeroDate = new DateTime();
$zeroDate->setDate(0, 0, 0);
$zeroDate->setTime(0, 0, 0);
$changedRow = BookQuery::create()->findPk($bookId)->setPublishedAt($zeroDate);
if($changedRow->isModified()) {
    try {
        $changedRow->save();
    } catch (Exception $exc) {
        $this->logger->debug(__METHOD__ . " " . $exc->getMessage());
    }
}

I have also tried this.

$changedRow = BookQuery::create()->findPk($bookId)->setPublishedAt("0000-00-00 00:00:00");
if($changedRow->isModified()) {
    try {
        $changedRow->save();
    } catch (Exception $exc) {
        $this->logger->debug(__METHOD__ . " " . $exc->getMessage());
    }
}

Both variants yield an error

Unable to execute UPDATE statement [...]: Invalid datetime format: 1292 Incorrect datetime value: '-0001-11-30 00:00:00' for column 'published_at' at row 1]

because of Propel trying to insert negative date-time values. How do I correctly reset these fields with Propel?


Solution

  • Updating the record by fireing the SQL directly worked as shown below.

    [...]
    
    try {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        $sql = "UPDATE `book` SET "
                . "`published_at`='0000-00-00 00:00:00' "
                . "WHERE id=".$bookId;
        $stmt = $con->prepare($sql);
        $stmt->execute();
    } catch(Exception $exc) {
        $this->logger->err(__METHOD__ . " " . $exc->getMessage());
    }
    
    [...]
    

    Although this solution works, it isn't a good practice, because it circumvents the use of more high-level functions provided by the ORM. A cleaner approach would be to let the value default to NULL instead of 0000-00-00 00:00:00 as mentioned by j0k in the comments to the question. But if your environment needs it, you can adapt the above code.