I have an action in a controller that simply retrieves the filename of an image from an id and then redirects to it.
This is working fine, but I noticed this approach broke almost every lightbox script (redirect I suppose), so I started thinking that maybe (most likely ) this is not the way to go.
Here’s the code:
public function actionView($id)
{
if (!is_numeric($id))
throw new CHttpException(404,'The requested page does not exist.');
$model = Images::model()->find('p_id = <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/tongue.gif' class='bbc_emoticon' alt=':P' />_id', array('<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/tongue.gif' class='bbc_emoticon' alt=':P' />_id'=>$id));
if($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
$this->redirect(Yii::app()->request->baseUrl . '/images/' . $model->filename);
}
Any ideas about how I can implement this one better?
My problem is that images are not stored in the database and reading them from the disk seems like a massive overhead because they can be quite big sometimes.
Use something like Amazon S3, grab a copy of the Yii S3 Extension and you’re good to go. Then you just need to store the image name and extension in the database and massively reduce the disk load and load times
A bit too much for this simple task, but this will come usefull in another project. Ty!
Yeah, I think I will end up with this solution. At least I will spare some db queries
Since I’m not that familiar with ActiveRecord , is that possible to extract all the values in a column (ie the ids of the posts) from a CActiveDataProvider? This way I’ll just make a SELECT IN in the images table before iterating on the posts.
I have a list of entries and I usually show n of those in a page. Each entry may have 0 or n images stored in a table like (id, entry_id, url).
I tryed the controller approach because it was handy to just have to call an action named view to show the image.
The entries are displayed using a foreach on the getData method of the data provider.
I may call the Images model inside the foreach but that will make n queries. It seems logical to retrieve a list with all the images before and then make the img tags as needed.
You know when you have an idea you cant see alternatives
If you need to retrieve records with related records, then use with()!
Example:
$models = MyClass::model()->with('images')->findAll();
foreach ($models as $model)
foreach ($model->images as $image)
echo CHtml::image($image->getFileUrl()); // add a custom method to get image url