Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

When you set a date field in Propel it goes to PropelDateTime, which is basically a DateTime object.

You code will generate a false date, because 0000-00-00 00:00:00 isn't a valid date:

<?php

$zeroDate = new DateTime();
$zeroDate->setDate(0, 0, 0);
$zeroDate->setTime(0, 0, 0);

var_dump($zeroDate);

// object(DateTime)#1 (3) { ["date"]=> string(20) "-0001-11-30 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

You can set a date in Propel to a non-valid date.

Why do you want to set a date to 0000-00-00 00:00:00? Why not null?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top