Last active
December 24, 2015 03:19
-
-
Save jaggy/6736657 to your computer and use it in GitHub Desktop.
CakePHP look-up table behaviour. Allows the user the `findOrCreate()` rails method≥
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
<?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