Skip to content

Commit

Permalink
Added ->saveRelationship(); ->saveRelationship() - That means you now…
Browse files Browse the repository at this point in the history
… can save a unique relationship without call ->save() (it does still work as aways but now with new features) - So now you can save only the relationships by calling ->saveRelationship() or a UNIQUE RELATIONSHIP by calling ->saveRelationship();
  • Loading branch information
klederson committed Feb 10, 2012
1 parent efe96d4 commit f2eec6a
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 84 deletions.
181 changes: 97 additions & 84 deletions app/libs/Dialect/Dialect.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function cacheSearch($field, $content, $condition = '==') {
} }


public function cacheSearchRegex($field, $pattern) { public function cacheSearchRegex($field, $pattern) {

} }


/** /**
Expand Down Expand Up @@ -124,18 +124,18 @@ public function fetch() {
public function dataExists($pointer) { public function dataExists($pointer) {
return is_array($this->dataSet[$pointer]) ? true : false; return is_array($this->dataSet[$pointer]) ? true : false;
} }

public function getDeclaredSelectableFields() { public function getDeclaredSelectableFields() {
if (count($this->getModel()->_select) > 0) { if (count($this->getModel()->_select) > 0) {

//Select based ONLY in the $obj->select(); method //Select based ONLY in the $obj->select(); method
foreach ($this->getModel()->_select as $index => $value) { foreach ($this->getModel()->_select as $index => $value) {
$fields .= empty($fields) ? "" : ", "; $fields .= empty($fields) ? "" : ", ";
$fields .= $value['alias'] != null ? sprintf("%s AS %s", $value['value'], $value['alias']) : sprintf("%s", $value['value']); $fields .= $value['alias'] != null ? sprintf("%s AS %s", $value['value'], $value['alias']) : sprintf("%s", $value['value']);

$declaredOnly = $declaredOnly != TRUE && $value['only'] != TRUE ? FALSE : TRUE; $declaredOnly = $declaredOnly != TRUE && $value['only'] != TRUE ? FALSE : TRUE;
} }

return array( return array(
'declaredOnly' => $declaredOnly, 'declaredOnly' => $declaredOnly,
'fields' => $fields 'fields' => $fields
Expand Down Expand Up @@ -187,13 +187,13 @@ public function prepareSelect($pk = null) {
$this->getModel()->join($value['field']['tableReference'], $value['field']['column'], $value['field']['column'], '=', 'JOIN', $tableLeft); $this->getModel()->join($value['field']['tableReference'], $value['field']['column'], $value['field']['column'], '=', 'JOIN', $tableLeft);
unset($classVars); unset($classVars);
} }

// Getting declared select fields/expressions // Getting declared select fields/expressions
$declaredSelect = $this->getDeclaredSelectableFields(); $declaredSelect = $this->getDeclaredSelectableFields();


// Define declared select into SELECT expression // Define declared select into SELECT expression
$fields .= $declaredSelect != FALSE ? $declaredSelect['fields'] : ''; $fields .= $declaredSelect != FALSE ? $declaredSelect['fields'] : '';

//Creating the selectable fields //Creating the selectable fields
if (!$declaredSelect['declaredOnly']) { if (!$declaredSelect['declaredOnly']) {
//Selecting from the map //Selecting from the map
Expand All @@ -204,7 +204,7 @@ public function prepareSelect($pk = null) {
$fields .= sprintf("%s.%s AS %s", $value['field']['tableReference'], $value['field']['column'], $index); $fields .= sprintf("%s.%s AS %s", $value['field']['tableReference'], $value['field']['column'], $index);
} }
} }
} elseif(!$declaredSelect['declaredOnly'] && empty($fields)) { } elseif (!$declaredSelect['declaredOnly'] && empty($fields)) {
$model = get_class($this->modelObj); $model = get_class($this->modelObj);
PhpBURN_Message::output("$model [!is not an mapped or valid PhpBURN Model!]", PhpBURN_Message::ERROR); PhpBURN_Message::output("$model [!is not an mapped or valid PhpBURN Model!]", PhpBURN_Message::ERROR);
exit; exit;
Expand Down Expand Up @@ -243,7 +243,7 @@ public function prepareSelect($pk = null) {
//Construct SQL //Construct SQL
$sql = $this->buildSELECTQuery($fields, $from, $joinString, $conditions, $whereConditions, $orderConditions, $groupConditions, $limit, $limits); $sql = $this->buildSELECTQuery($fields, $from, $joinString, $conditions, $whereConditions, $orderConditions, $groupConditions, $limit, $limits);
unset($fieldInfo, $fields, $from, $joinString, $conditions, $whereConditions, $orderBy, $orderConditions, $limit, $pkField, $parentFields, $parentClass, $groupConditions); unset($fieldInfo, $fields, $from, $joinString, $conditions, $whereConditions, $orderBy, $orderConditions, $limit, $pkField, $parentFields, $parentClass, $groupConditions);

return $sql; return $sql;
} }


Expand All @@ -261,17 +261,17 @@ public function getFromString() {
} }


public function getWhereString($pk, $pkField) { public function getWhereString($pk, $pkField) {

if (count($this->getModel()->_where) > 0) { if (count($this->getModel()->_where) > 0) {


foreach ($this->getModel()->_where as $index => $value) { foreach ($this->getModel()->_where as $index => $value) {
//Checking swhere and where //Checking swhere and where
if (!empty($value['mwhere'])) { if (!empty($value['mwhere'])) {
//Normal where //Normal where
// THIS FIXES GROUPS WHEN MANUAL WHERE HAVE AND/OR CONDITION BUT HAVE NO PREDECESSOR // THIS FIXES GROUPS WHEN MANUAL WHERE HAVE AND/OR CONDITION BUT HAVE NO PREDECESSOR
if(empty($whereConditions[$value['group']])) if (empty($whereConditions[$value['group']]))
$value['mwhere'] = preg_replace('(^(([ ]+)?AND|OR) )', ' ', $value['mwhere']); $value['mwhere'] = preg_replace('(^(([ ]+)?AND|OR) )', ' ', $value['mwhere']);

$whereConditions[$value['group']] .= ( $value['mwhere'] ); $whereConditions[$value['group']] .= ( $value['mwhere'] );
} else { } else {
//SuperWhere //SuperWhere
Expand Down Expand Up @@ -307,17 +307,17 @@ public function getWhereString($pk, $pkField) {
if ($pk != null) { if ($pk != null) {
$pk = gettype($pk) == "string" ? addslashes($pk) : $pk; $pk = gettype($pk) == "string" ? addslashes($pk) : $pk;
$pk = is_numeric($pk) ? $pk : sprintf("'%s'", $pk); $pk = is_numeric($pk) ? $pk : sprintf("'%s'", $pk);

$whereConditions[$this->getModel()->_defaultWhereGroup] .= empty($whereConditions[$this->getModel()->_defaultWhereGroup]) ? sprintf('%s.%s= %s ', $this->getModel()->_tablename, $pkField['field']['column'], $pk) : sprintf(" AND %s.%s= %s ", $this->getModel()->_tablename, $pkField['field']['column'], ($pk)); $whereConditions[$this->getModel()->_defaultWhereGroup] .= empty($whereConditions[$this->getModel()->_defaultWhereGroup]) ? sprintf('%s.%s= %s ', $this->getModel()->_tablename, $pkField['field']['column'], $pk) : sprintf(" AND %s.%s= %s ", $this->getModel()->_tablename, $pkField['field']['column'], ($pk));
} }


if(is_array($whereConditions)) { if (is_array($whereConditions)) {
foreach($whereConditions as $conditions) { foreach ($whereConditions as $conditions) {
$finalConditions .= !empty($finalConditions) ? ' AND ' : ''; $finalConditions .=!empty($finalConditions) ? ' AND ' : '';
$finalConditions .= sprintf(' ( %s ) ', $conditions); $finalConditions .= sprintf(' ( %s ) ', $conditions);
} }
} }

return $finalConditions; return $finalConditions;
} }


Expand Down Expand Up @@ -443,72 +443,85 @@ public function save() {
$this->getMap()->setFieldValue($field['field']['alias'], $lastId); $this->getMap()->setFieldValue($field['field']['alias'], $lastId);
} }


$this->saveRelationships();

return true;
} else {
return false;
}
}

public function saveRelationships($name = NULL) {
if($name == NULL) {
foreach ($this->getMap()->fields as $fieldCheck => $infos) { foreach ($this->getMap()->fields as $fieldCheck => $infos) {
if ($this->getModel()->getMap()->getRelationShip($fieldCheck) == true && $this->getModel()->$fieldCheck instanceof $infos['isRelationship']['foreignClass']) { if ($this->getModel()->getMap()->getRelationShip($fieldCheck) == true && $this->getModel()->$fieldCheck instanceof $infos['isRelationship']['foreignClass']) {
$this->saveRelationship($infos, $fieldCheck);
}
}
} else {
$infos = $this->getMap()->fields[$name];
$this->saveRelationship($infos, $name);
}
}

protected function saveRelationship(&$infos, &$fieldCheck) {


// Just to short name // Just to short name
$relModel = &$this->getModel()->$fieldCheck; $relModel = &$this->getModel()->$fieldCheck;


// Checking the kind of relationship // Checking the kind of relationship
switch ($infos['isRelationship']['type']) { switch ($infos['isRelationship']['type']) {
case PhpBURN_Core::ONE_TO_ONE: case PhpBURN_Core::ONE_TO_ONE:
$this->getModel()->$fieldCheck->save(); $this->getModel()->$fieldCheck->save();
$this->getModel()->getMap()->setFieldValue($infos['isRelationship']['thisKey'], $relModel->getMap()->getFieldValue($infos['isRelationship']['thisKey'])); $this->getModel()->getMap()->setFieldValue($infos['isRelationship']['thisKey'], $relModel->getMap()->getFieldValue($infos['isRelationship']['thisKey']));
$this->getModel()->save(); $this->getModel()->save();
break; break;


case PhpBURN_Core::ONE_TO_MANY: case PhpBURN_Core::ONE_TO_MANY:
$relModel->getMap()->setFieldValue($infos['isRelationship']['relKey'], $this->getModel()->getMap()->getFieldValue($infos['isRelationship']['relKey'])); $relModel->getMap()->setFieldValue($infos['isRelationship']['relKey'], $this->getModel()->getMap()->getFieldValue($infos['isRelationship']['relKey']));
$this->getModel()->$fieldCheck->save(); $this->getModel()->$fieldCheck->save();
break; break;


case PhpBURN_Core::MANY_TO_MANY: case PhpBURN_Core::MANY_TO_MANY:
$this->getModel()->$fieldCheck->save(); $this->getModel()->$fieldCheck->save();


// SEARCH IF THE RELATIONSHIP ALREADY EXISTS // SEARCH IF THE RELATIONSHIP ALREADY EXISTS
unset($sqlWHERE, $relationshipSQL, $rs); unset($sqlWHERE, $relationshipSQL, $rs);
$relKeyVal = $this->getModel()->getMap()->getFieldValue($infos['isRelationship']['relKey']); $relKeyVal = $this->getModel()->getMap()->getFieldValue($infos['isRelationship']['relKey']);
$relOutKeyVal = $relModel->getMap()->getFieldValue($infos['isRelationship']['relOutKey']); $relOutKeyVal = $relModel->getMap()->getFieldValue($infos['isRelationship']['relOutKey']);


$sqlWHERE = sprintf("%s.%s = '%s'", $infos['isRelationship']['relTable'], $infos['isRelationship']['relKey'], addslashes($relKeyVal)); $sqlWHERE = sprintf("%s.%s = '%s'", $infos['isRelationship']['relTable'], $infos['isRelationship']['relKey'], addslashes($relKeyVal));
$sqlWHERE .= " AND "; $sqlWHERE .= " AND ";
$sqlWHERE .= sprintf("%s.%s = '%s'", $infos['isRelationship']['relTable'], $infos['isRelationship']['outKey'], addslashes($relOutKeyVal)); $sqlWHERE .= sprintf("%s.%s = '%s'", $infos['isRelationship']['relTable'], $infos['isRelationship']['outKey'], addslashes($relOutKeyVal));


$relationshipSQL = sprintf('SELECT * FROM %s WHERE %s', $infos['isRelationship']['relTable'], $sqlWHERE); $relationshipSQL = sprintf('SELECT * FROM %s WHERE %s', $infos['isRelationship']['relTable'], $sqlWHERE);


$rs = $this->execute($relationshipSQL); $rs = $this->execute($relationshipSQL);
if ($this->getModel()->getConnection()->affected_rows() == 0) { if ($this->getModel()->getConnection()->affected_rows() == 0) {
unset($sqlWHERE, $relationshipSQL, $rs); unset($sqlWHERE, $relationshipSQL, $rs);
$relationshipSQL = sprintf("INSERT INTO %s ( %s, %s ) VALUES ( '%s' , '%s' ) ", $infos['isRelationship']['relTable'], $infos['isRelationship']['relKey'], $infos['isRelationship']['relOutKey'], $relKeyVal, $relOutKeyVal); $relationshipSQL = sprintf("INSERT INTO %s ( %s, %s ) VALUES ( '%s' , '%s' ) ", $infos['isRelationship']['relTable'], $infos['isRelationship']['relKey'], $infos['isRelationship']['relOutKey'], $relKeyVal, $relOutKeyVal);
$rs = $this->execute($relationshipSQL); $rs = $this->execute($relationshipSQL);
} else if($this->getModel()->getConnection()->affected_rows() > 0 && class_exists($infos['isRelationship']['relTable'])) { } else if ($this->getModel()->getConnection()->affected_rows() > 0 && class_exists($infos['isRelationship']['relTable'])) {
$relModel = new $infos['isRelationship']['relTable']; $relModel = new $infos['isRelationship']['relTable'];


$relModel->$infos['isRelationship']['relKey'] = $relKeyVal; $relModel->$infos['isRelationship']['relKey'] = $relKeyVal;
$relModel->$infos['isRelationship']['relOutKey'] = $relOutKeyVal; $relModel->$infos['isRelationship']['relOutKey'] = $relOutKeyVal;


if($relModel->find() > 0) { if ($relModel->find() > 0) {
$relModel->fetch(); $relModel->fetch();


foreach($relModel->toArray() as $relFieldName => $value) { foreach ($relModel->toArray() as $relFieldName => $value) {
$_name = sprintf('_rel_%s', $relFieldName); $_name = sprintf('_rel_%s', $relFieldName);
if(isset($this->getModel()->$_name)) if (isset($this->getModel()->$_name))
$relModel->$relFieldName = $this->getModel()->$_name; $relModel->$relFieldName = $this->getModel()->$_name;
} }


$relModel->save(); $relModel->save();
}
}

// @TODO maybe this is a nice place to put save relationship data to reltable
break;
} }
} }
}


return true; // @TODO maybe this is a nice place to put save relationship data to reltable
} else { break;
return false;
} }
} }


Expand Down Expand Up @@ -538,7 +551,7 @@ public function prepareInsert() {
$insertValues[$infos['field']['tableReference']] .= sprintf("'%s'", addslashes($value)); $insertValues[$infos['field']['tableReference']] .= sprintf("'%s'", addslashes($value));
} }
} else if ($this->getModel()->getMap()->getRelationShip($field) == true && !empty($this->getModel()->$field)) { } else if ($this->getModel()->getMap()->getRelationShip($field) == true && !empty($this->getModel()->$field)) {

} }
} }


Expand All @@ -557,25 +570,25 @@ public function prepareInsert() {
public function prepareUpdate() { public function prepareUpdate() {
//Searching for compound PKs or all Pks ( including parent and childs ones ) //Searching for compound PKs or all Pks ( including parent and childs ones )
$pkFields = &$this->getMap()->getPrimaryKey(FALSE); $pkFields = &$this->getMap()->getPrimaryKey(FALSE);

$updatedFields = null; $updatedFields = null;
//Checking each MAPPED field looking in cache for changes in field value, if existis it will be updated, if not we just update the right fields //Checking each MAPPED field looking in cache for changes in field value, if existis it will be updated, if not we just update the right fields
foreach ($this->getMap()->fields as $field => $infos) { foreach ($this->getMap()->fields as $field => $infos) {
if ($this->getModel()->getMap()->getRelationShip($field) != true && ( isset($this->getModel()->getMap()->fields[$infos['field']['alias']]) && $this->getModel()->$infos['field']['alias'] != $infos['#fetch_value'] ) ) { if ($this->getModel()->getMap()->getRelationShip($field) != true && ( isset($this->getModel()->getMap()->fields[$infos['field']['alias']]) && $this->getModel()->$infos['field']['alias'] != $infos['#fetch_value'] )) {
$this->getMap()->setFieldValue($field, $this->getModel()->$field); $this->getMap()->setFieldValue($field, $this->getModel()->$field);
$updatedFields[$infos['field']['tableReference']] .= $updatedFields[$infos['field']['tableReference']] == null ? '' : ', '; $updatedFields[$infos['field']['tableReference']] .= $updatedFields[$infos['field']['tableReference']] == null ? '' : ', ';
$updatedFields[$infos['field']['tableReference']] .= sprintf("%s='%s'", $infos['field']['column'], addslashes($this->getModel()->$field)); $updatedFields[$infos['field']['tableReference']] .= sprintf("%s='%s'", $infos['field']['column'], addslashes($this->getModel()->$field));

// Prepare the wehere for one or many pk fields // Prepare the wehere for one or many pk fields
if(is_array($pkFields)) { if (is_array($pkFields)) {
foreach($pkFields as $pkFname => $pkArray) { foreach ($pkFields as $pkFname => $pkArray) {
$pkWhere[$pkArray['field']['tableReference']] .= !empty($pkWhere[$pkArray['field']['tableReference']]) ? "AND" : ""; $pkWhere[$pkArray['field']['tableReference']] .=!empty($pkWhere[$pkArray['field']['tableReference']]) ? "AND" : "";
$pkWhere[$pkArray['field']['tableReference']] .= sprintf(" %s = '%s'",$pkFname, $pkArray['#fetch_value']); $pkWhere[$pkArray['field']['tableReference']] .= sprintf(" %s = '%s'", $pkFname, $pkArray['#fetch_value']);
} }
} }
} }
} }

//Define sqls based on each table from the parent to the child //Define sqls based on each table from the parent to the child
if (count($updatedFields) > 0) { if (count($updatedFields) > 0) {
foreach ($updatedFields as $index => $updatedFieldsUnique) { foreach ($updatedFields as $index => $updatedFieldsUnique) {
Expand Down
4 changes: 4 additions & 0 deletions app/libs/Model.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -629,6 +629,10 @@ public function get($pk = null) {
public function save() { public function save() {
return $this->getDialect()->save(); return $this->getDialect()->save();
} }

public function saveRelationship($name) {
$this->getDialect()->saveRelationships($name);
}


/** /**
* Delete an entry * Delete an entry
Expand Down

0 comments on commit f2eec6a

Please sign in to comment.