Saturday, November 8, 2014

Check if data exist in Yii

We can use findByAttributes to verify or check if a certain data exist in our database.
$id = 12;//We are going to check if id = 12 exist
$checkData = User::model()->findByAttributes(array('id'=> $id));
if (isset($checkData)) {
 echo 'record  exist';
} else {   
 echo 'record does not exist';
} 
note that you must change
User::model()->findByAttributes(array('id'=> $id));
 
to your proper target model, for example you are going to find data in Post, the code must look like this
 Post::model()->findByAttribute(array('author_id'=> $id));
note: you must also change the id to the proper attribute that you are looking for in the database , for example the codes above shows that we are finding the author_id that has an id of 12.

No comments:

Post a Comment