Welcome Guest, Not a member yet? Register   Sign In
Can I have 2 tables in codeigniter 4 model?
#1

Hello

In CI v.3x I used (and I was used it extensively) the following code:


Code:
        public function __construct()
        {
            parent::__construct();
            $this->table_name = ('faq');
            $this->primary_key = ('faqID');
            $this->order_by = ('faqcategoryID, faqSorder DESC');
            // my vars, used in joins, to get the category name
            $this->table_name2 = ('faqcategory');
            $this->foreign_key = ('faqcategoryID');
            $this->parent_name = ('faqcategoryName');
        }   // end of constructor function
           
    }



So later, in the MyModel I was able to call funciton getWithCategories like this:

Code:
public function get_with_category ($table_name2 = FALSE, $parent_name = FALSE, $foreign_key = FALSE, $order_by = FALSE)
       {
   
           $data = array();
          
           $query = $this->db->query("SELECT $this->table_name. * , $this->table_name2.$this->parent_name
                                      FROM $this->table_name
                                      LEFT JOIN $this->table_name2
                                      ON ( $this->table_name.$this->foreign_key = $this->table_name2.$this->foreign_key)
                                      ORDER BY $this->order_by");
        
           if($query->num_rows() > 0)
           {
              
               foreach($query->result_array() as $row)
               {
                  
                   $data[] = $row; 
               }
           }
         
           $query->free_result();
          
           return $data;
          
       } // end of function get_with_category

The role of this function was to provide me with the category name for each pair of related tables. In this example I have the faq and faq category name, but I used this for each and every case where I needed to get the category name (news, articles, etc).

Is there any way to implement this in CodeIgniter 4? I checked the documentation but I didn't find a way to have 2 tables in one model. Any idea how could I create similar reusable function in CI 4?
Reply


Messages In This Thread
Can I have 2 tables in codeigniter 4 model? - by t_5810 - 10-28-2020, 06:52 AM



Theme © iAndrew 2016 - Forum software by © MyBB