insert
是沒有太多的選項。因此,Expression mysql NOW() in Doctrine QueryBuilder的答案顯示了手動知道該變量的內容。
這需要最近發佈的DBAL> = 2.5。 2014年你會不走運。請注意,datetime
是一個有效的字符串,但似乎沒有常數http://php.net/manual/en/pdo.constants.php。
public function insert($params) {
if (!isset($params[static::CREATED_ON])) {
$params[] = [static::CREATED_ON, new \Datetime('now'), 'datetime'];
}
if (!isset($params[static::MODIFIED_ON])) {
$params[] = [static::MODIFIED_ON, new \Datetime('now'), 'datetime'];
}
$conn = $this->_dbs['write'];
$query_builder = $conn->createQueryBuilder();
$query_builder->insert(static::TABLE);
foreach ($params as $location => $data) {
$field = $data[0];
$value = $data[1];
$type = (isset($data[2])) ? $data[2] : \PDO::PARAM_STR;
$prep = (isset($data[3])) ? $data[3] : '?';
$query_builder
->setValue($field, $prep)
->setParameter($location, $value, $type);
}
$return = $query_builder->execute();
if (!$return) {
throw new \Exception("Failed to execute statement");
}
return $conn->lastInsertId();
}
public function update($params, $where) {
$conn = $this->_dbs['write'];
$query_builder = $conn->createQueryBuilder();
$query_builder->update(static::TABLE);
foreach ($params as $location => $data) {
// can do arbitrary expressions via ['field', null, null, 'ANY EXPRESSION YOU WANT']
// ie ['votes', null, null,'votes=votes+25']
// or ['votes', '1', \PDO::PARAM_INT, 'votes + ?']
$field = $data[0];
$value = $data[1];
$type = (isset($data[2])) ? $data[2] : \PDO::PARAM_STR;
$prep = (isset($data[3])) ? $data[3] : '?';
$query_builder
->set($field, $prep)
->setParameter($location, $value, $type);
}
$query_builder->where($where);
return $query_builder->execute();
}
如果你把'CURRENT_TIMESTAMP()'放在那裏呢? – zerkms
你應該嘗試Doctrine TimeStampable ... https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/timestampable.md – Jean
@zerkms我也嘗試過也沒有運氣。我看到有幾個地方認爲這會起作用。 –