Is there a way to check whether a entity is referenced in a foreign table (check foreign key relationship existence) and get the entities or ids from these foreign tables that are related?
Here is the situation: I have a bunch of entities to delete. But some of them can be referenced in other tables. I'm working in a generic way, so I don't know which model I'm working with neither what are the linkings It has. What I want is to filter these entities that can't be deleted and get the entities or ids from the foreign tables that are associated to the model I'm working so I can show them after the proccess.
The code would be basically in this way:
public function removeEntities($table_alias, $data){
$data = $this->checkData($data); //do some work...
$table_object = TableRegistry::get($table_alias);
// here I'd like to get the entities or ids from tables related to $table_object that can't be deleted
$data = $this->check_relationship($table_object, $data);
$table_object->deleteAll(["common_index IN" => $data["to_delete"]]); //remove the guys that are related to nobody
return $data["cant_delete"]; //return the foreign entities/ids which are related to entities from $table_object
}
If I wasn't clear, please help me at comments. It was very hard for me to develop this question.
Suppose I'm working with Companies
and I have to delete some of them:
I have a list of companies to remove, but I can remove just the ones that are not related to Workers
and Clients
. Also, I want to retrieve the Workers
and Clients
that are linked.