I'd like some help please. I have these two database tables, with relationship 1-n (one album has many images):
albums images
---------- -------------
album_id img_id
title album_id
description img_file
Now what I'm trying to do is to show all the albums with their images in my view, something like this, see the 2nd screenshot (portfolio).
This is what I have in my Controller:
// fetch all album data
$albums = $this->album_model->get();
// fetch images for each album
foreach ($albums as $album ) {
$images = $this->albumimage_model->get_by('album_id', $album->album_id);
}
$data = array(
'albums' => $albums,
'images' => $images,
);
$this->load->view('album_listing', $data);
If i loop through the album data in my view, I get this:
<?php foreach($albums as $album): ?>
<div class="album">
<p><?php echo $album->title; ?></p>
<p><?php echo $album->description; ?></p>
<div>
<?php endforeach; ?>
So far so good, but now here comes the headache: I want to display the images that belong to each album, so basicle something like this:
<?php foreach($albums as $album): ?>
<div class="album">
<p><?php echo $album->title; ?></p>
<p><?php echo $album->description; ?></p>
// show all images of the album
<div class="images"><img src="uploads/<php? echo $album->title; ?>.'/'.<php? echo $image->image_file; ?> " /></div>
<div>
<?php endforeach; ?>
How can I accomplish that, according to the CodeIgniter practices???
Some additional info: 1. I have also enable the CodeIgntier's Profiler and I've noticed that the running queries are incremented like this. Whouldn't this increase the memmory in case I have many albums (50 - 100 albums with images)???
I also tried to do this using just one query with JOIN, something like this:
$albums = $this->db->select('albums.*') ->select('images.img_id, images.img_file') ->join('images', 'images.album_id = albums.album_id') ->order_by('albums.album_id') ->get('albums') ->result_array();
The problem with this is when I loop through the data (lets say I have two albums in my database), I get the data twice on my page, like :
album1 - images of album 1
album1 - images of album 1
album2 - images of album 2
album2 - images of album 2
$query = $this->db->get('albums');
$albums = $query->result_array();
$query = $this->db->get('images');
$images =$query->result_array();
foreach ($albums as $album)
{
foreach ($images as $image)
{
if($image['album_id'] == $album['album_id']){
$data[$album['album_id']]['images'] = $image['album_id'];
}
}
}
var_dump($data);