problema al cargar multiple archivos

hola, como estan tengo algo de tiempo trabajando con yii, y ps este es el dia y aun hay cosas que no comprendo.

mi problema es el siguiente,quiero crear un producto el cual tiene muchas imagenes asociadas a el, osea en la tabla imgProducto esxiste una clave foranea que hace referencia al id de la tabla producto.

hasta ahi todo bien, el problema es que cuando intento subir algun registro, guarda varios registros con el mismo nombre, igual al numero de atributos que tiene la tabla producto.

Acontinucion muestro el codigo:

ProductoController/actionCreate




/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

	$model=new Producto;  // this is my model related to table


        if(isset($_POST['Producto'])) {


            $model->attributes=$_POST['Producto'];


            // THIS is how you capture those uploaded images: remember that in your CMultiFile widget, you set 'name' => 'images'


            $images = CUploadedFile::getInstancesByName('img');

            $model->save();

            // proceed if the images have been set

            if (isset($images) && count($images) > 0) {


                // go through each uploaded image

                foreach ($images as $image => $pic) {


                    if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/productos/'.$pic->name)) {

                        // add it to the main model now

                        $img_add = new ImgProducto();

                        $img_add->url = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model

                        $img_add->Producto_id = $model->id; // this links your picture model to the main model (like your user, or profile model)

                        $img_add->save(); // DONE

                    } else

                        $this->render('error', $error);

                }

                // save the rest of your information from the form

                if ($model->save()) {

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

                }

            }

        }

   $this->render('create',array('model'=>$model,));


}




[b]

_form[/b]





<div class="container">

<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'producto-form',

	// Please note: When you enable ajax validation, make sure the corresponding

	// controller action is handling ajax validation correctly.

	// There is a call to performAjaxValidation() commented in generated controller code.

	// See class documentation of CActiveForm for details on this.

	'htmlOptions' => array('enctype' => 'multipart/form-data'), // ADD THIS

	'enableAjaxValidation'=>true,

)); ?>


	<p class="note">Campos con <span class="required">*</span> son requeridos.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<div class="col-sm-4">

		<?php echo $form->labelEx($model,'nombre'); ?>

		<?php echo $form->textField($model,'nombre',array('size'=>45,'maxlength'=>45,'class'=>'form-control')); ?>

		<?php echo $form->error($model,'nombre'); ?>


		<?php echo $form->labelEx($model,'descripcion'); ?>

		<?php echo $form->textArea($model,'descripcion',array('size'=>60,'maxlength'=>140,'class'=>'form-control')); ?>

		<?php echo $form->error($model,'descripcion'); ?>


		<?php echo $form->labelEx($model,'precio'); ?>

		<?php echo $form->textField($model,'precio',array('class'=>'form-control')); ?>

		<?php echo $form->error($model,'precio'); ?>


		<?php echo $form->labelEx($model,'descuento'); ?>

		<?php echo $form->textField($model,'descuento',array('class'=>'form-control')); ?>

		<?php echo $form->error($model,'descuento'); ?>


	<div class="row">

		<div class="col-sm-6">

		<?php echo $form->labelEx($model,'estado'); ?>

		<?php echo $form->checkBox($model,'estado'); ?>

		<?php echo $form->error($model,'estado'); ?>

		</div>

		<div class="col-sm-6">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Guardar' : 'Actualizar',array('class'=>'btn btn-primary')); ?>

		</div>

	</div>

	</div>

	<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.'/js/fileInput/fileinput.js') ?>

	<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.'/js/fileInput/fileinput_locale_es.js') ?>


	<div class="col-sm-8">

		<?php echo $form->labelEx($model,'img'); ?>

		<input id="img" name="img[]" type="file" multiple class="file-loading">

	</div>

        </div>

<?php $this->endWidget(); ?>

</div>


<?php Yii::app()->clientScript->registerScript('upfile','

     $("#img").fileinput({

         language:"es",

        maxFileSize: 1000,

        initialCaption: "Selecciona los Productos",

        overwriteInitial: false,

         showUpload: false,

         browseIcon: "<i></i>",

         validateInitialCount: true,

    });'); ?>



_view




<?php

/* @var $this ProductoController */

/* @var $data Producto */

?>


<div class="col-sm-3 box-producto" >


	<?php echo CHtml::link(


	'<h1>'.CHtml::encode($data->nombre).'</h1>', array('view', 'id'=>$data->id)); ?>

	<br />


<?php if ($data->descuento!=0) {?>

		<div class="descuento-producto">

			<?php echo CHtml::encode($data->descuento).'%'; ?>

		</div>

		<?php }


		$i=0;

		$nombreFoto=array();


		 foreach ($data->imgProductos as $key):

			 $nombreFoto[$i] = $key->url;

		 endforeach;

echo CHtml::link(

 CHtml::image(Yii::app()->baseUrl.'/images/productos/'.$nombreFoto[0],

 			$nombreFoto[0],

 			array('style'=>'width:100%;text-align: center;')),

 array('view', 'id'=>$data->id));


 			?>




<div class="pie_producto">




	<?php if ($data->precio!=0) {

		if ($data->descuento!=0) {?>

			<div class="precio-producto">

				<?php echo '<b>Bs.</b> <del>'.CHtml::encode($data->precio).'</del>'; ?>

			</div>

	<?php	} else{?>

			<div class="precio-producto">

				<?php echo '<b>Bs.</b>'.CHtml::encode($data->precio); ?>

			</div>

	<?php

	}

} ?>








	<?php if ($data->estado==1) {


		echo '<p class="text-success"><b>Disponible</b></p>';

	}else

		echo '<p class="text-danger"><b>Agotado</b></p>'; ?>


	<?php //$valor=Yii::app()->dateFormatter->format("d MMMM y ",strtotime($data->fecha));?>


		<?php //echo CHtml::encode($valor); ?>


</div>

</div>






la verdad me da pena pedir ayuda porque nunca aporto nada… pero estoy que e arrano los pelos jejej

Buenas.

En primer lugar estás haciendo 2 saves del modelo de productos. Esto no tiene sentido en una acción create, y menos en tu código. No modificas nada del modelo entre saves.

Segundo, en dónde te guarda los registros, en la tabla de productos o en la de imágenes?

Tercero, qué quieres decir con que guarda tantos registros como atributos tiene la tabla producto? que si la tabla producto tiene 50 campos, te guarda 50 registros?!?!?!?

Explica un poco más claro tu problema, por favor.

Un saludo.