Check Foreign Key and Delete

Hey Guys,

I want to delete user but before delete it will check foreign key other tables, if data exist related to that user then display message… How to do that?

This is not working. Don’t understand where is the problem

public function actionDelete()

{


	if(Yii::app()->request->isPostRequest)


	{


		// we only allow deletion via POST request


		//$this->loadModel()->delete();


		$model = $this->loadModel();


		$profile = Test::model()->findAll();


		if ($profile->User_id == $model->id)


		{


			echo "sorry";


			


		} else {


			$model->delete();


			


		}





		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser


		if(!isset($_GET['ajax']))


			$this->redirect(array('index'));


	}


	else


		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');


}

Hi,

well, what exactly isn’t working?

You cannot do this. findAll() will return a list of active records, not only a single one.

You could try something like this to check for related entries:




$profiles = Test::model()->findAllByAttributes(array('User_id'=>$model->id));

if(count($profiles) > 0) {

    echo "Sorry, but there are still related items!";

}

else { $model->delete(); }



Regards

Thanks. Working