Model->Save() Duplication Issue


I’ve created an import function in my module which is triggered by an action.

The database is SQLite

The flow are as follows

Action: InitializeModule

This action has no form and will redirect to another action after completing the initialization of the module.

public function actionInitialize()


	$module = $this->module;






InitializeModule method:

The method checks if a field is set in my parameter table. If not set it will create a record and start importing data from files located in a folder located within the module structure.

Each file is read line by line, i.e "sfi18n";"ISO";"en";"ISO"

The first field (sfi18n) identifies the unique key in my category table.

For each line, I check if the category exists and if it doesn’t I create it.

The code are as follows:

public static function findOrCreateCategory($categoryName)


        // Search for categry

	$category = Category::model()->findByAttributes(array('CategoryId' => $categoryName));


	if (!isset($category->CategoryId))


		$category = new Category();


		$category->CategoryId = $categoryName;

		$category->Name   	= $categoryName;





	return $category;


For some reason the two first times it enters this method it will create a record. The rest of the times it finds the category and ignores the insert.

The result in my table is to identical records (even though I have CategoryId as uniqe key and and unique index on the field)

I’ve also tried creating an SQL command but it made no differnce.

Does anyone know where I should start looking?

Have you tried with if(empty($category)) ? Since you really only want to insert a new line if it doesn’t exist. It looks like it might be that isset() is returning false because the property in itself doesn’t exist within the active record. The property might be returned by a getter and __isset() might not be implemented (this is just a wild guess).

It was the same result. :-[

I’m starting to wonder if it could be something with the files that I import.

Even though they look the same, there must be a difference. If i mix in other category id’s I do not get duplicate records.

I will learn to live with the duplicate record :blink: and move on to other functionality

findByAttributes() returns null if no records is found… so the best check should be if($category===null)…

If you still get duplicates then the "keys" are different.