/** * Update a single instance * * @param One_Model $model */ public function update(One_Model $model) { $scheme = One_Repository::getScheme($model->getSchemeName()); $db = $this->db($scheme); // @TODO update query should be done in the renderer // determine table to insert into $table = $this->getTable($scheme); $sql = "UPDATE `" . $table . "` SET "; //create clauses $modified = $model->getModified(); $modifiedRelations = $model->getModifiedRelations(); $data = new stdClass(); foreach ($scheme->get('attributes') as $attName => $at) { if (isset($modified[$attName])) { $data->{$attName} = $modified[$attName]; } } // Check for relationships (FK values), cannot use attribute but must use column or link name // JL 06JAN2008 - Three possible situations, two are needed: // * ManyToOne // * The FK is a field in the model's record // * We need to set this field BEFORE saving the record // * ManyToMany // * Relations are in a separate table // * We should set them AFTER saving the record (especially when inserting a new record) // * OneToMany // * Not needed for now - When editing, we'll usually edit the child and select it's parent $mtos = array(); foreach ($scheme->getLinks() as $link) { if ($link->getAdapterType() == "manytoone") { $fk = $link->fk(); if (isset($modified[$fk])) { $data->{$fk} = $modified[$fk]; $mtos[$fk] = $modified[$fk]; } } } $clauses = array(); foreach ($scheme->get('attributes') as $attName => $at) { if (isset($modified[$attName])) { $clauses[] = One_Query_Renderer::getInstance('mysql')->formatAttribute($at, $modified[$attName]); } } if (count($mtos) > 0) { foreach ($mtos as $k => $v) { $clauses[] = '`' . $k . '` = "' . mysql_real_escape_string($v) . '"'; } } $sql .= implode(', ', $clauses); $idAttr = $scheme->getIdentityAttribute(); $id = $idAttr->getName(); $value = $model->{$id}; $value = $idAttr->toString($value); $data->{$id} = $value; $sql .= " WHERE " . $id . ' = ' . $data->{$id}; // Don't perform the update if no updates have to be performed if (count($clauses) > 0) { if (mysql_query($sql, $db) === false) { throw new One_Exception('Update failed: ' . mysql_error($db)); } } // Handle ManyToMany relations foreach ($scheme->getLinks() as $link) { if ($link->getAdapterType() == "manytomany") { if (isset($modifiedRelations[$link->getName()])) { $model->saveRelated($link); } } } }
/** * Return the One_Renderer for this One_Store * * @return One_Renderer */ protected function getRenderer() { // Must return a new instance every time as in rare cases some joins or selectfields or ... // from a different query will be reused leading to unwanted queries return One_Query_Renderer::getInstance('mysql'); }