• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Join one to many

I have to tables:

gallery -> id_gallery, name, desc, data


images -> gallery_id, name,path

One gallery can have many images. I need to select all galleries and all images and on view page present all galleries and all images which contains that gallery. How can do this?

I have code like this for now:

$q = $this->db->select('*')->from('gallery')->join('images','images.gallery_id = gallery.id_gallery')->get();
  return $q = $q->result_array();

And foreach loop in view:

<?php foreach ($gallery as $gal):  ?>
    <a href="&lt;?php echo IMG ?&gt;galerija/&lt;?php echo $gal['name'] ?&gt;/&lt;?php echo $gal['path'] ?&gt;" rel="galerija[slike]" class="figure_img">
    <img src="&lt;?php echo IMG ?&gt;galerija/&lt;?php echo $gal['naziv'] ?&gt;/thumbs/&lt;?php echo $gal['path'] ?&gt;" >
    <figcaption>&lt;?php echo $gal['name']; ?&gt;</figcaption>
    &lt;?php endforeach; ?&gt;

This foreach loop is producing 5 figure tags instead of one (if gallery have 5 images for example). I need to create one figure tag, and inside it I need to create a tag for every image in that gallery. How can I do this?

Here's a quick & dirty possibility (but the better solution is to set this all up as separate methods in a model):

$galleryQuery = $this->db->get('gallery');
foreach ($galleryQuery->result_array() as $key => $row) {
    $data[$key] = $row;
    $this->db->where('gallery_id', $row['id_gallery']);
    $imgQuery = $this->db->get('images');
    $data[$key]['images'] = $imgQuery->result_array();  
return $data;

View: ( I assume each gallery goes with one figure tag)

foreach($data as $gallery) { ?&gt;
         foreach($gallery['image'] as $image) {
             /* code for whatever you do with each image in the figure */


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.