Skip to content

Instantly share code, notes, and snippets.

@jaggy
Last active December 24, 2015 03:19
Show Gist options
  • Save jaggy/6736657 to your computer and use it in GitHub Desktop.
Save jaggy/6736657 to your computer and use it in GitHub Desktop.
CakePHP look-up table behaviour. Allows the user the `findOrCreate()` rails method≥
<?php
class LookupTableBehavior extends ModelBehavior{
/**
* Finds and returns the data or inserts it to the database
*
* @param Model $model
* @param string $value
* @param string $field
*
* @return array|boolean
*/
public function findOrCreate(Model $model, $value, $field = 'name'){
$data = [$field => $value];
$result = $model->find('first', [
'conditions' => $data
]);
if($result) return $result[$model->alias]['id'];
$model->create();
$result = $model->save($data);
return ($result) ? $result[$model->alias]['id'] : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment