Search code examples
mysqlcodeignitermany-to-many

I need help for Many to Many relation database


I am Using CI with hmvc..

I have 3 tables:

Table 1:

s_id | s_name | s_date

Table 2:

n_id | n_name | n_date

Table 3 contains the relation between table 1 and table 2:

s_id | n_id

I want to fetch values in table 1 or table 2 by ids.

Once I have n_id of table 2, I want to find and to fetch the related values in table 3 and table 1. The related values match by having the same ids.

Please help.


Solution

  • I think this might work for you. I have done something similar in the past while using CI. This is an Active Records query that should be in your model. This query can be shortened but I made it verbose so you see what is going on.

     public function get_ids($n1_id){
        $this->db->select('*');
        $this->db->from('table_3');
        $this->db->join('table_2', 'table_2.n1_id = table_3.n1_id');
        $this->db->join('table_1', 'table.s1_id = table_3.s1_id');
        $this->db->where('n1_id', $n1_id);
        $query = $this->db->get();
        return $query;
    }
    

    Basically once you have one of the id's you can pass it in as a parameter and select all the rows from table 3 that matches the id. Then join table 1 and table 2 on the matching rows in table 3.

    Let me know if this works. I have not make the tables to test it.