Skip to content

Instantly share code, notes, and snippets.

@oshanz
Created February 11, 2016 06:08
Show Gist options
  • Save oshanz/738913b45654a8d7e64e to your computer and use it in GitHub Desktop.
Save oshanz/738913b45654a8d7e64e to your computer and use it in GitHub Desktop.
checkConstraints
protected function checkConstraints($entity, $key)
{
$query = "SELECT TABLE_NAME, COLUMN_NAME
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = :schema
AND REFERENCED_TABLE_NAME = :table
AND REFERENCED_COLUMN_NAME = :column";
$stmt = $this->em->getConnection()->prepare($query);
$stmt->bindValue('schema', $this->em->getConnection()->getDatabase());
$stmt->bindValue('table', $this->em->getMetadataFactory()->getMetadataFor($entity)->table['name']);
$stmt->bindValue('column', 'id');
$stmt->execute();
$count = $stmt->rowCount();
if (0 == $count) {// no one use as a foreign key
return false;
}
$data = $stmt->fetchAll(\PDO::FETCH_OBJ);
$query = "SELECT 1 FROM {$data[0]->TABLE_NAME} WHERE {$data[0]->COLUMN_NAME} = $key";
for ($i = 1, $l = count($data); $i < $l; $i++) {
$query .= " UNION ALL SELECT 1 FROM {$data[$i]->TABLE_NAME} WHERE {$data[$i]->COLUMN_NAME} = $key";
}
$stmt = $this->em->getConnection()->prepare($query);
$stmt->execute();
return $stmt->rowCount();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment