Sasha
Sasha

Reputation: 8705

Codeigniter 2.1 - join one to many

I have to tables:

gallery -> id_gallery, name, desc, data

and:

images -> gallery_id, name

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:

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

EDIT:

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

This foreach loop is producing 5 div tags instead of one (if gallery have 5 images for example).

Upvotes: 0

Views: 1476

Answers (1)

Venkata Krishna
Venkata Krishna

Reputation: 4305

If you want to select all the images from images table for all galleries..........

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

or in the other way. Write a model function and in that

public function get_images()

 {
    $res=$this->db->query("select * from images and gallery where gallery.id_gallery = images.gallery_id");
    if($res->num_rows()>0){
        return $res->result("array");
    }

    return array();

}

Upvotes: 3

Related Questions