How To Store Image Id In Relational Table

Hi,

I’ve managed to create my first image upload script. I’m using the CMultiFileUpload widget to upload attached images to my Blog post.

In the BlogsController.php i’ve got the actionUpdate like this:




public function actionUpdate($id)

{

  $model=$this->loadModel($id);

  

  if(isset($_POST['Blogs']))

  {

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

    

    // saving images.

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

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

    {

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

      {	

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

        {

          $image = new Images();

          $image->name = $pic->name; 

          $image->hash = md5($pic->name.time()); 

          if(!$image->save())

            die(print_r($image->getErrors())); // temp way of error checking.	

        }                    

      }

    }


    if($model->save())

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

			

  }

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

}



Works great, my Images class creates a record in my images table.

But I also got a relational table blog_images. In this table i store the image_id and the blog_id.

How do i create this record? Just with a simple query or do I have to make a method in the Blogs model who handle this? Or do I even have to create a BlogsImages model, just for this? I’m confused. :huh:

BTW to fetch the images i use the great relations method in the Blogs model.




public function relations()

{

  return array('images' => array(self::MANY_MANY, 'Images',

               'blog_images(blog_id,image_id)'),

	      );

}



Any help by pointing me in the right direction is appreciated! :)

Well, I’ve created a new model BlogImages and add a few lines to the saving images part in the actionUpdate.




...

$image = new Images();

$image->name = $pic->name; 

$image->hash = md5($pic->name.time()); 

if(!$image->save())

  die(print_r($image->getErrors()));


// new:						

$blog_image = new BlogImages();

$blog_image->blog_id = $id;

$blog_image->image_id = $image->primaryKey;  

$blog_image->save(); 



Seems to be te right way to do this. Correct me if i’m wrong please!

That’s the way I’d handle it; I think the logic belongs in the controller.