Created
October 23, 2011 09:50
-
-
Save iamFIREcracker/1307191 to your computer and use it in GitHub Desktop.
CakePHP function which validate foreign keys
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
/** | |
* Check if a given foreign key exists in the model (given its name). | |
*/ | |
public function validateForeignKey($field){ | |
$associations = array_map( | |
create_function('$v', 'return $v["foreignKey"];'), | |
$this->belongsTo | |
); | |
$aliases = array(); | |
foreach($associations as $model => $foreignKey) { | |
if (!array_key_exists($foreignKey, $aliases)) | |
$aliases[$foreignKey] = array(); | |
array_push($aliases[$foreignKey], $model); | |
} | |
foreach ($aliases[key($field)] as $model) { | |
$count = $this->{$model}->find('count', array( | |
'conditions' => array( | |
$model . '.' . $this->{$model}->primaryKey => current($field) | |
), | |
'recursive' => -1 | |
)); | |
if ($count == 1) | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works in cakephp 1.3.