Created
September 24, 2014 13:33
-
-
Save thinkingmedia/8b85f275f48ac22814e9 to your computer and use it in GitHub Desktop.
My take on your code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function saveKeyValues(Model $Model, $data){ | |
if(empty($data) || !isset($data[$Model->alias]) || empty($data[$Model->alias])) | |
{ | |
return false; | |
} | |
$optionKey = $this->options[$Model->alias]['fields']['key']; | |
$optionValue = $this->options[$Model->alias]['fields']['value']; | |
// I don't understand this part. | |
$dataTemplate = array($Model->alias => array()); | |
foreach ($data[$Model->alias] as $field => $value) { | |
if ($Model->hasField($field)) { | |
$dataTemplate[$Model->alias][$field] = $value; | |
unset($data[$Model->alias][$field]); | |
} | |
} | |
$belongsTo = reset($Model->belongsTo); | |
if(empty($belongsTo)) | |
{ | |
return false; | |
} | |
$index = 0; | |
foreach ($data[$Model->alias] as $key => $value) { | |
$index++; | |
//check existing key value | |
$existing = $Model->find('first', array( | |
'conditions' => array( | |
$belongsTo['foreignKey'] => $data[$belongsTo['foreignKey']], | |
$optionKey => $key | |
), | |
'fields'=>array('id') | |
)); | |
$insert = $dataTemplate; | |
if(!empty($existing)) | |
{ | |
// cake will do update if id is set, otherwise a create. | |
$insert[$Model->alias]['id'] = $existing['id']; | |
} | |
$insert[$Model->alias][$optionKey] = $key; | |
$insert[$Model->alias][$optionValue] = $value; | |
$insert[$Model->alias][$belongsTo['foreignKey']] = $data[$belongsTo['foreignKey']]; | |
if (false === $Model->save($insert)) { | |
return false; | |
} | |
if($index == count($data[$Model->alias])){ | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment