insert
isn't much of an option. So the answer at Expression mysql NOW() in Doctrine QueryBuilder shows manually knowing what's coming for that variable.
This requires DBAL >= 2.5 which was recently released. You'd be out of luck in 2014. Note that datetime
is a valid string, but doesn't appear to have a constant 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();
}