Skip to content

Instantly share code, notes, and snippets.

@iamFIREcracker
Created October 23, 2011 09:50
Show Gist options
  • Save iamFIREcracker/1307191 to your computer and use it in GitHub Desktop.
Save iamFIREcracker/1307191 to your computer and use it in GitHub Desktop.
CakePHP function which validate foreign keys
/**
* 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;
}
@felixmaier1989
Copy link

'User' should be replaced with $Model->alias

Plus here's how to use this rule in the model:

public $validate = array(
	'user_id' => array(
		'validateForeignKey' => array(
			'rule' => array('validateForeignKey', 'User'),
			'message' => 'Please enter a valid user.'
		),
	),
);

@hoolahoop
Copy link

This works in cakephp 1.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment