Active records exists in loop

Hello everybody, I am new in this community and with Yii also.

Here is my problem:

I want to save in my database multiple rows. Before inserting each row in the database I want to check if a record with the identical title and date exists already.

So I used the exists function.

The problem:

The problem is that the exists function returns always the same value after the first loop no matter what I did.

(I tried the refresh function too)

I read documentation and searched the forums already but I couldnt find a proper solution.

I would also like to mention that it is not a problem of the object, the objects renews its values, the exists funtion doesn’t.

Thank you very much in advance.

It’s difficult to say what could be the problem, but the first thing I can think of is that you have some error in your code logic… so

if you can post your code, we can check it…

Ofcourse, here is the code.




<?php 

foreach ($objTree as $anObject)

		{

			

			

			$entry = new Entry;

			

			$attrs = array(

			'title' => $anObject->title,

			'price' => $anObject->price,

		

			);

			

			$entry->attributes= $attrs;

			$exists = Entry::model()->exists('strcmp(title,:title )',array(':title'=> $anObject->title));

			

			if(!empty($exists))

			{

				 $output =  'exists';

				 

				

			}

			else

			{

				

				if($entry->save())

				{  

					$output = 'Success ';

					

				}

				else

				{  

					$output = 'Error ';}				

				}

			return $output;

			

			

		}

?>



I think you’re betteroff just doing a simple find on your criteria.

Anotheroption, if you’re using MySQL, is to use the ON DUPLICATE KEY UPDATE clause in conjunction with a unique constraint.

Thank you very much for your reply. I will try this one.

The loop will only go through one iteration since you have a return statement inside it.