Search code examples
codeigniterjoinmodelmany-to-manyloose-coupling

How do I keep models loosely coupled when querying a many-to-many table in CodeIgniter?


I'm using CodeIgniter and have three tables and a model for each:

  • User - table of users
  • Product - table of products
  • UserProduct - table showing which users have which products (two foreign key columns, and some other columns such as date)

In my code I want to display a list for a particular user showing which products they have. So I have a method in the UserProduct class that does a select on the UserProduct table matching for the userId, and a join bringing in all the data I need about each product.

This works fine, but I am concerned now that I am moving down a path of tight coupling. For example, say I want to find out the URL of a product image. I have a method in the product model to return this, I don't want a duplicate method in the UserProduct model, and I don't want to create a coupling by having the UserProduct model trying to access methods in other models (which I don't think CodeIgniter likes you to do).

This problem seems likely to occur in any model that accesses a DB table that has foreign keys where that model may need data from the parent table and want to manipulate it.

Is there an elegant solution, or do I need to accept that foreign keys necessarily create couplings in models or the need for similar methods across models?

TIA, Phil.


Solution

  • My personal standard is to create 1 controller + 1 model always.

    for example site.com/users will use model_users.php or site.com/products will use model_products.php

    to slim your code and re-use methods use methods params for example a model method to be re-used could be:

    function getUsers($data){
     foreach($data as $key=>$value){
      $this->db->where($key,$value);
    }
    $query = $this->db->get('users');
    return $query->result();
    }
    

    the more you extend this method the more you can re-use, just another example of extending:

     function getUsers($data,$order_by = false){
         foreach($data as $key=>$value){
          $this->db->where($key,$value);
        }
     if($order_by){
      foreach($order_by as $key=>$value){
      $this->db->order_by($key,$value);
      }
      }
        $query = $this->db->get('users');
        return $query->result();
        }
    
    //then you call results with this in your controller
       $results =  $this->model->getUsers(
          $data = array('id'=>'12','country'=>'USA'),
           $order_by = array('username'=>'DESC')
         );
    

    so now you got also order_by , and so on, you can add joins, limit,offset,like etc.. all in the same or quite the same way , the more accurated you are the more you can re-use the same methods