Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JOIN three tables in Codeigniter

Tags:

I'm using codeigniter framework to develop one music cms. i have 3 tables in mysql database, Currently im working in "Album" Table and "Model, Controller". i want to SELECT "Album" Table 1 and JOIN "Album" -> "cat_id" with "Category" -> "cat_id", and fetch all categories records.

Then i want to JOIN "Album" -> "album_id" on "Soundtrack" -> "album_id" then fetch all soundtrack records A to Z.

Please somebody help me to show proper codeigniter query, how i can SELECT and JOIN Tables then fetch records from 3 tables, ?

Table 1 -> Category

  • cat_id

  • cat_name

  • cat_title
  • date

    Table 2 -> Album

  • cat_id
  • album_id

  • album_title

  • album_details

    Table 3 -> Soundtrack

  • album_id

  • track_title

  • track_url
  • date
like image 316
Ahmed iqbal Avatar asked Jan 31 '14 11:01

Ahmed iqbal


2 Answers

Use this code in model

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    if($query->num_rows() != 0)
    {
        return $query->result_array();
    }
    else
    {
        return false;
    }
}
like image 54
Shibu Thomas Avatar answered Sep 19 '22 14:09

Shibu Thomas


try this

In your model

If u want get all album data use

  function get_all_album_data() {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $query = $this->db->get ();
    return $query->result ();
 }

if u want to get specific album data use

  function get_album_data($album_id) {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $this->db->where ( 'Album.album_id', $album_id);
    $query = $this->db->get ();
    return $query->result ();
 }
like image 36
codeigniter leaner Avatar answered Sep 20 '22 14:09

codeigniter leaner