Advertisement
bkader

CodeIgniter 3 MY_Model.php

Dec 10th, 2015
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 21.74 KB | None | 0 0
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. /**
  5.  * CodeIgniter Base Model.
  6.  *
  7.  * @package     CodeIgniter
  8.  * @category    Core Extension
  9.  * @author  Kader Bouyakoub <bkader@mail.com>
  10.  * @link    https://github.com/bkader
  11.  * @link    https://twitter.com/KaderBouyakoub
  12.  */
  13. class MY_Model extends CI_Model
  14. {
  15.     /**
  16.      * holds the current model class name.
  17.      * @var string
  18.      */
  19.     protected $model = null;
  20.  
  21.     /**
  22.      * holds the current db group.
  23.      * @var string
  24.      */
  25.     protected $db_group;
  26.  
  27.     /**
  28.      * instance of $this->db object.
  29.      * @var object
  30.      */
  31.     protected $database;
  32.  
  33.     /**
  34.      * current table name set or guessed.
  35.      * @var string
  36.      */
  37.     protected $table = null;
  38.  
  39.     /**
  40.      * array of current table fields.
  41.      * @var array
  42.      */
  43.     protected $fields = array();
  44.  
  45.     /**
  46.      * holds the current table's primary key.
  47.      * @var string
  48.      */
  49.     protected $primary_key = null;
  50.  
  51.     /**
  52.      * how is data returned? As array of object.
  53.      * @var string
  54.      */
  55.     protected $return_type = 'object';
  56.  
  57.     /**
  58.      * whether to use unix_timestamp or mysql datetime.
  59.      * @var boolean
  60.      */
  61.     protected $unix_timestamp = true;
  62.  
  63.     /**
  64.      * use this format when using mysql datetime.
  65.      * @var string
  66.      */
  67.     protected $datetime_format = 'Y-m-d H:i:s';
  68.  
  69.     /**
  70.      * column that holds the date of creation.
  71.      * @var string
  72.      */
  73.     protected $created_at = 'created_at';
  74.  
  75.     /**
  76.      * column that holds the date of update.
  77.      * @var string
  78.      */
  79.     protected $updated_at = 'updated_at';
  80.  
  81.     /**
  82.      * whether to remove the record or update the column of deletion.
  83.      * @var boolean
  84.      */
  85.     protected $soft_delete = false;
  86.  
  87.     /**
  88.      * column that holds the date of deletion.
  89.      * @var string
  90.      */
  91.     protected $deleted_at = 'deleted_at';
  92.  
  93.     /**
  94.      * if set to TRUE, retrieve deleted records as well.
  95.      * @var boolean
  96.      */
  97.     protected $even_deleted = false;
  98.  
  99.     /**
  100.      * if set to TRUE, retrieve only deleted records.
  101.      * @var boolean
  102.      */
  103.     protected $only_deleted = false;
  104.  
  105.     /**
  106.      * attributes that will be removed from data before insert or update.
  107.      * @var array
  108.      */
  109.     protected $protected_attributes = array();
  110.  
  111.     /**
  112.      * whether to skip form validation or not.
  113.      * @var boolean
  114.      */
  115.     protected $skip_validation = false;
  116.  
  117.     /**
  118.      * array of form validation rules.
  119.      * @var array
  120.      */
  121.     protected $validation_rules = array();
  122.  
  123.     /**
  124.      * before and after observers.
  125.      */
  126.     protected $before_create = array();
  127.     protected $before_update = array();
  128.     protected $before_delete = array();
  129.     protected $before_find   = array();
  130.     protected $after_create = array();
  131.     protected $after_update = array();
  132.     protected $after_delete = array();
  133.     protected $after_find   = array();
  134.  
  135.     /**
  136.      * holds the array of data that will be used before insert or update.
  137.      * @var array|false
  138.      */
  139.     protected $data = false;
  140.  
  141.     /**
  142.      * holds the result of query before returning it.
  143.      * @var mixed
  144.      */
  145.     protected $result = false;
  146.  
  147.     /**
  148.      * relationship getter.
  149.      * @var array
  150.      */
  151.     protected $with = array();
  152.  
  153.     /**
  154.      * Contains any related objects of which this model
  155.      * is singularly related.
  156.      * @var array
  157.      */
  158.     protected $has_one = array();
  159.  
  160.     /**
  161.      * Contains any related objects of which this model
  162.      * is related one or more times.
  163.      * @var array
  164.      */
  165.     protected $has_many = array();
  166.  
  167.     /**
  168.      * class constructor
  169.      *
  170.      * @return  void
  171.      */
  172.     public function __construct()
  173.     {
  174.         parent::__construct();
  175.         $this->model = ucfirst(get_class($this));
  176.         $this->_fetch_table();
  177.         $this->_set_database();
  178.         $this->_fetch_fields();
  179.         $this->_set_primary_key();
  180.         $this->_set_soft_delete();
  181.  
  182.         // default observers if none are set.
  183.         array_unshift($this->before_create, 'protect_attributes', 'created_at');
  184.         array_unshift($this->before_update, 'protect_attributes', 'updated_at');
  185.     }
  186.  
  187.     // ------------------------------------------------------------------------
  188.  
  189.     /**
  190.      * override methods call to create additional special ones :D.
  191.      */
  192.     public function __call($method, $params)
  193.     {
  194.         // No table set? Nothing to do.
  195.         if (empty($this->table))
  196.         {
  197.             show_error("Table name is not set for '{$this->model}' class.");
  198.         }
  199.  
  200.         // The method exists in this class? Call it.
  201.         elseif (method_exists($this, $method))
  202.         {
  203.             return call_user_func_array(array($this, $method), $params);
  204.         }
  205.  
  206.         // Add methods to observers.
  207.         elseif (preg_match('/^before_([^)]+)$/', $method, $m))
  208.         {
  209.             if (isset($this->{$m[0]}) && is_array($this->{$m[0]}))
  210.             {
  211.                 is_array($params[0]) && $params = $params[0];
  212.  
  213.                 foreach ($params as $param)
  214.                 {
  215.                     array_push($this->{$m[0]}, $param);
  216.                 }
  217.             }
  218.  
  219.             return $this;
  220.         }
  221.  
  222.  
  223.         // Retrieve by a given column name?
  224.         elseif (preg_match('/^find_by_([^)]+)$/', $method, $m) && count($m) == 2)
  225.         {
  226.             $field = $m[1];
  227.             $match = array_shift($params);
  228.  
  229.             if (strpos($field, '_or_'))
  230.             {
  231.                 $field = explode('_or_', $field);
  232.             }
  233.  
  234.             $result = false;
  235.  
  236.             if (is_array($field))
  237.             {
  238.                 $_params = $params;
  239.                 foreach ($field as $_field)
  240.                 {
  241.                     array_unshift($_params, $_field, $match);
  242.                     if ($found = call_user_func_array(array($this, 'find_by'), $_params))
  243.                     {
  244.                         $result = $found;
  245.                         break;
  246.                     }
  247.                     $_params = $params;
  248.                 }
  249.             }
  250.             else
  251.             {
  252.                 array_unshift($params, $field, $match);
  253.                 $result = call_user_func_array(array($this, 'find_by'), $params);
  254.             }
  255.  
  256.             return $result;
  257.         }
  258.  
  259.         // Retrieve multiple records by a given column name?
  260.         elseif (preg_match('/^find_many_by_([^)]+)$/', $method, $m) && count($m) == 2)
  261.         {
  262.             array_unshift($params, $m[1]);
  263.             return call_user_func_array(array($this, 'find_many'), $params);
  264.         }
  265.  
  266.         // Update a row using update_by() method
  267.         elseif ((preg_match('/^update_by_([^)]+)$/', $method, $m)
  268.             OR preg_match('/^delete_by_([^)]+)$/', $method, $m))
  269.             && count($m) == 2)
  270.         {
  271.             $method = str_replace("_{$m[1]}", '', $method);
  272.             array_unshift($params, $m[1]);
  273.             return call_user_func_array(array($this, $method), $params);
  274.         }
  275.  
  276.         // No need to create the method, we use the existing one.
  277.         elseif ($method == 'update_many' OR $method == 'delete_many')
  278.         {
  279.             $method = str_replace('many', 'by', $method);
  280.             return call_user_func_array(array($this, $method), $params);
  281.         }
  282.  
  283.         // Update multiple records using update_many() method
  284.         elseif ((preg_match('/^update_many_by_([^)]+)$/', $method, $m)
  285.             OR preg_match('/^delete_many_by_([^)]+)$/', $method, $m))
  286.             && count($m) == 2)
  287.         {
  288.             $method = str_replace("many_by_{$m[1]}", 'by', $method);
  289.             array_unshift($params, $m[1]);
  290.             return call_user_func_array(array($this, $method), $params);
  291.         }
  292.  
  293.         // Remove records even if $soft_delete is set to true.
  294.         elseif (strpos($method, 'remove') === 0)
  295.         {
  296.             $method = str_replace('remove', 'delete', $method);
  297.             $this->soft_delete = false;
  298.             return call_user_func_array(array($this, $method), $params);
  299.         }
  300.  
  301.         elseif (method_exists($this->database, $method))
  302.         {
  303.             return call_user_func_array(array($this->database, $method), $params);
  304.         }
  305.  
  306.         // No method found? Show error.
  307.         else
  308.         {
  309.             show_error("Method $method() does not exist in class {$this->model}");
  310.         }
  311.     }
  312.  
  313.     // ------------------------------------------------------------------------
  314.     // INTERNAL METHODS
  315.     // ------------------------------------------------------------------------
  316.  
  317.     /**
  318.      * Attempts to guess table's name if not set.
  319.      */
  320.     private function _fetch_table()
  321.     {
  322.         if ($this->table == null)
  323.         {
  324.             // Load inflector helper.
  325.             function_exists('plural') OR $this->load->helper('inflector');
  326.             $this->table = plural(preg_replace('/(_m|_model)?$/', '', strtolower($this->model)));
  327.         }
  328.     }
  329.  
  330.     /**
  331.      * prepares database object.
  332.      */
  333.     private function _set_database()
  334.     {
  335.         if ($this->db_group !== null)
  336.         {
  337.             $this->database = $this->load->database($this->db_group, true, true);
  338.         }
  339.         else
  340.         {
  341.             if ( ! isset($this->db) or ! is_object($this->db))
  342.             {
  343.                 $this->load->database('', false, true);
  344.             }
  345.         }
  346.         $this->database = $this->db;
  347.     }
  348.  
  349.     /**
  350.      * prepares an array of table's columns.
  351.      */
  352.     private function _fetch_fields()
  353.     {
  354.         if (is_object($this->database) && $this->table != null && $this->table != 'mies')
  355.         {
  356.             $this->fields = $this->database->list_fields($this->table);
  357.         }
  358.     }
  359.  
  360.     /**
  361.      * try to guess the primary key if not set
  362.      */
  363.     private function _set_primary_key()
  364.     {
  365.         if ($this->table != null && $this->table != 'mies' && $this->primary_key == null)
  366.         {
  367.             $this->primary_key = $this->database->query("SHOW KEYS FROM `".$this->table."` WHERE Key_name = 'PRIMARY'")->row()->Column_name;
  368.         }
  369.     }
  370.  
  371.     /**
  372.      * try to guess if soft delete should be turned on or not.
  373.      */
  374.     private function _set_soft_delete()
  375.     {
  376.         if (is_object($this->database) && $this->table != null)
  377.         {
  378.             $this->soft_delete = in_array($this->deleted_at, $this->fields);
  379.  
  380.         }
  381.     }
  382.  
  383.     /**
  384.      * remove protected attributes form data
  385.      */
  386.     public function protect_attributes()
  387.     {
  388.         foreach ($this->protected_attributes as $attr)
  389.         {
  390.             if (is_object($this->data))
  391.             {
  392.                 unset($this->data->{$attr});
  393.             }
  394.             else
  395.             {
  396.                 unset($this->data[$attr]);
  397.             }
  398.         }
  399.     }
  400.  
  401.     /**
  402.      * returns the array of table's columns.
  403.      */
  404.     public function list_fields()
  405.     {
  406.         if (empty($this->fields))
  407.         {
  408.             $this->_fetch_fields();
  409.         }
  410.  
  411.         return $this->fields;
  412.     }
  413.  
  414.     /**
  415.      * prepare the return type.
  416.      */
  417.     private function return_type($multi = false)
  418.     {
  419.         $method = $multi ? 'result' : 'row';
  420.         $method .= ($this->return_type == 'array') ? '_array' : '';
  421.         return $method;
  422.     }
  423.  
  424.     /**
  425.      * validate data before insert or update using CI form validation.
  426.      */
  427.     public function validate()
  428.     {
  429.         $data = $this->data;
  430.  
  431.         if ($this->skip_validation === false && ! empty($this->validation_rules))
  432.         {
  433.             foreach ($this->validation_rules as $key => $val)
  434.             {
  435.                 $_POST[$key] = $val;
  436.             }
  437.  
  438.             // Load form validation only if it's not loaded.
  439.             if ( ! class_exists('CI_Form_validation', false))
  440.             {
  441.                 $this->load->library('form_validation');
  442.             }
  443.  
  444.             if (is_array($this->validation_rules))
  445.             {
  446.                 $this->form_validation->set_rules($this->validation_rules);
  447.  
  448.                 if ($this->form_validation->run() == true)
  449.                 {
  450.                     $this->data = $data;
  451.                 }
  452.                 else
  453.                 {
  454.                     $this->data = false;
  455.                 }
  456.             }
  457.             else
  458.             {
  459.                 if ($this->form_validation->run($this->validation_rules) == true)
  460.                 {
  461.                     $this->data = $data;
  462.                 }
  463.                 else
  464.                 {
  465.                     $this->data = false;
  466.                 }
  467.             }
  468.         }
  469.  
  470.         $this->data = $data;
  471.     }
  472.  
  473.     /**
  474.      * triggers and event on $data or $result
  475.      */
  476.     public function trigger($event, $data = array())
  477.     {
  478.         if (isset($this->{$event}) && is_array($this->{$event}))
  479.         {
  480.             foreach ($this->{$event} as $method)
  481.             {
  482.                 call_user_func_array(array($this, $method), $data);
  483.             }
  484.         }
  485.     }
  486.  
  487.     /**
  488.      * Set time() depending on the property $this->unix_timestamp
  489.      */
  490.     protected function set_datetime()
  491.     {
  492.         if ($this->unix_timestamp === true)
  493.         {
  494.             return time();
  495.         }
  496.  
  497.         return date($this->datetime_format);
  498.     }
  499.  
  500.     /**
  501.      * Add date of creation to $data before insert.
  502.      */
  503.     protected function created_at()
  504.     {
  505.         if (is_object($this->data) && empty($this->data->{$this->created_at}))
  506.         {
  507.             $this->data->{$this->created_at} = $this->set_datetime();
  508.         }
  509.         elseif (is_array($this->data) && empty($this->data[$this->created_at]))
  510.         {
  511.             $this->data[$this->created_at] = $this->set_datetime();
  512.         }
  513.     }
  514.  
  515.     /**
  516.      * Add date of update to $data before update.
  517.      */
  518.     protected function updated_at()
  519.     {
  520.         if (is_object($this->data) && empty($this->data->{$this->updated_at}))
  521.         {
  522.             $this->data->{$this->updated_at} = $this->set_datetime();
  523.         }
  524.         elseif (is_array($this->data) && empty($this->data[$this->updated_at]))
  525.         {
  526.             $this->data[$this->updated_at] = $this->set_datetime();
  527.         }
  528.     }
  529.  
  530.     /**
  531.      * Prepares WHERE clause.
  532.      */
  533.     public function set_where()
  534.     {
  535.         $args = func_get_args();
  536.  
  537.         if ( ! empty($args))
  538.         {
  539.             $field = array_shift($args);
  540.             $match = is_array($field) ? null : array_shift($args);
  541.  
  542.             if (is_array($match))
  543.             {
  544.                 $this->database->where_in($field, $match);
  545.             }
  546.             else
  547.             {
  548.                 $this->database->where($field, $match);
  549.             }
  550.         }
  551.  
  552.         // If there are still arguments, use them for select().
  553.         if ( ! empty($args))
  554.         {
  555.             $this->database->select($args);
  556.         }
  557.  
  558.         // We make sure to exclude deleted records
  559.         if ($this->even_deleted === true)
  560.         {
  561.             $this->soft_delete = false;
  562.         }
  563.  
  564.         if ($this->soft_delete === true)
  565.         {
  566.             if ($this->only_deleted === true)
  567.             {
  568.                 $this->database->where("$this->deleted_at >=", 1);
  569.             }
  570.             else
  571.             {
  572.                 $this->database->where($this->deleted_at, 0);
  573.             }
  574.         }
  575.  
  576.         // By returning this, we allow chaining
  577.         return $this;
  578.     }
  579.  
  580.     /**
  581.      * retrieve deleted records as well.
  582.      */
  583.     public function even_deleted()
  584.     {
  585.         $this->even_deleted = true;
  586.         return $this;
  587.     }
  588.  
  589.     /**
  590.      * retrieves deleted records only.
  591.      */
  592.     public function only_deleted()
  593.     {
  594.         $this->only_deleted = true;
  595.         return $this;
  596.     }
  597.  
  598.     public function get($table = null)
  599.     {
  600.         $table OR $table = $this->table;
  601.         return $this->database->get($table);
  602.     }
  603.  
  604.     // ------------------------------------------------------------------------
  605.     // INSERT METHODS
  606.     // ------------------------------------------------------------------------
  607.  
  608.     /**
  609.      * Inserts a new record and returns its ID.
  610.      */
  611.     public function insert(array $data = array(), $validate = true)
  612.     {
  613.         $this->data = $data;
  614.         $validate && $this->validate();
  615.  
  616.         $this->trigger('before_create');
  617.  
  618.         if ($this->database->insert($this->table, $this->data))
  619.         {
  620.             $insert_id = $this->database->insert_id();
  621.             $this->trigger('after_create', $insert_id);
  622.             return $insert_id;
  623.         }
  624.  
  625.         return false;
  626.     }
  627.  
  628.     /**
  629.      * inserts multiple records and returns an array if IDs.
  630.      */
  631.     public function insert_many(array $data = array(), $validate = true)
  632.     {
  633.         $ids = array();
  634.  
  635.         foreach ($data as $_data)
  636.         {
  637.             $ids[] = $this->insert($_data, $validate);
  638.         }
  639.  
  640.         return $ids;
  641.     }
  642.  
  643.     // ------------------------------------------------------------------------
  644.     // FINDERS
  645.     // ------------------------------------------------------------------------
  646.  
  647.     /**
  648.      * Retrieves a single record by its primary value with optional select.
  649.      */
  650.     public function find()
  651.     {
  652.         $args = func_get_args();
  653.  
  654.         if ( ! empty($args))
  655.         {
  656.             array_unshift($args, $this->primary_key);
  657.             return call_user_func_array(array($this, 'find_by'), $args);
  658.         }
  659.  
  660.         return false;
  661.     }
  662.  
  663.     /**
  664.      * Retrieves a single record by $field=$match condition with option select.
  665.      */
  666.     public function find_by()
  667.     {
  668.         call_user_func_array(array($this, 'set_where'), func_get_args());
  669.        
  670.         $this->result = $this->get($this->table);
  671.        
  672.         if ($this->result->num_rows() == 1)
  673.         {
  674.             $result = $this->result->{$this->return_type()}();
  675.             $result = $this->relate($result);
  676.             return $result;
  677.         }
  678.  
  679.         return false;
  680.     }
  681.  
  682.     /**
  683.      * Retrieves multiple records by WHERE clause with optional select argument.
  684.      */
  685.     public function find_many()
  686.     {
  687.         call_user_func_array(array($this, 'set_where'), func_get_args());
  688.        
  689.         $this->result = $this->get($this->table);
  690.        
  691.         if ($this->result->num_rows() >= 1)
  692.         {
  693.             return $this->result->{$this->return_type(true)}();
  694.         }
  695.  
  696.         return false;
  697.     }
  698.  
  699.     // ------------------------------------------------------------------------
  700.     // UPDATES
  701.     // ------------------------------------------------------------------------
  702.  
  703.     /**
  704.      * updates a single record by its primary key value.
  705.      */
  706.     public function update()
  707.     {
  708.         $args = func_get_args();
  709.         if ( ! empty($args))
  710.         {
  711.             array_unshift($args, $this->primary_key);
  712.             return call_user_func_array(array($this, 'update_by'), $args);
  713.         }
  714.  
  715.         return false;
  716.     }
  717.  
  718.     /**
  719.      * updates a single record by WHERE clause.
  720.      */
  721.     public function update_by()
  722.     {
  723.         $args = func_get_args();
  724.  
  725.         if (empty($args))
  726.         {
  727.             return false;
  728.         }
  729.  
  730.         // $data is always at the end.
  731.         $this->data = array_pop($args);
  732.         if ( ! is_array($this->data) OR empty($this->data))
  733.         {
  734.             return false;
  735.         }
  736.  
  737.         $this->trigger('before_update');
  738.  
  739.         $this->skip_validation OR $this->validate();
  740.  
  741.         if ($this->data !== false)
  742.         {
  743.             call_user_func_array(array($this, 'set_where'), $args);
  744.             $this->database->update($this->table, $this->data);
  745.             $result = ($this->database->affected_rows() > 0);
  746.             $this->trigger('after_update', array($this->data, $result));
  747.             return $result;
  748.         }
  749.  
  750.         return false;
  751.     }
  752.  
  753.     // ------------------------------------------------------------------------
  754.     // DELETES
  755.     // ------------------------------------------------------------------------
  756.  
  757.     /**
  758.      * Delete a row from the table by the primary value
  759.      */
  760.     public function delete($primary_value)
  761.     {
  762.         return $this->delete_by($this->primary_key, $primary_value);
  763.     }
  764.  
  765.     /**
  766.      * Delete a row from the database table by an arbitrary WHERE clause
  767.      */
  768.     public function delete_by()
  769.     {
  770.         call_user_func_array(array($this, 'set_where'), func_get_args());
  771.  
  772.         if ($this->soft_delete === true)
  773.         {
  774.             $datetime = $this->set_datetime();
  775.             $this->database->update(
  776.                 $this->table,
  777.                 array($this->deleted_at => $datetime)
  778.             );
  779.         }
  780.         else
  781.         {
  782.             $this->database->delete($this->table);
  783.         }
  784.  
  785.         $result = ($this->database->affected_rows() > 0);
  786.         $this->trigger('after_delete', $result);
  787.         return $result;
  788.     }
  789.  
  790.     // ------------------------------------------------------------------------
  791.     // RELATIONSHIPS
  792.     // ------------------------------------------------------------------------
  793.  
  794.     /**
  795.      * adds a relation ship.
  796.      */
  797.     public function with($relation)
  798.     {
  799.         $args = str_replace(' ', '', explode(',', $relation));
  800.         foreach ($args as $arg)
  801.         {
  802.             $this->with[] = $arg;
  803.         }
  804.         return $this;
  805.     }
  806.  
  807.     /**
  808.      * creates table's relationships
  809.      */
  810.     protected function relate($row)
  811.     {
  812.         function_exists('singular') OR $this->load->helper('inflector');
  813.         // Loop through has_one in order to
  814.         // get data from the related table
  815.         if ( ! empty($this->has_one) and is_array($this->has_one))
  816.         {
  817.             foreach ($this->has_one as $key => $value)
  818.             {
  819.                 $options = array();
  820.  
  821.                 if (is_string($value))
  822.                 {
  823.                     $relationship = $value;
  824.                     $options['model'] = isset($options['model'])
  825.                                         ? $options['model']
  826.                                         : plural($value).'_model';
  827.                 }
  828.                 else
  829.                 {
  830.                     $relationship = $key;
  831.                     $options      = $value;
  832.                 }
  833.                 $options['local'] = isset($options['local'])
  834.                                     ? $options['local']
  835.                                     : $this->primary_key;
  836.                 $options['foreign'] = isset($options['foreign'])
  837.                                     ? $options['foreign']
  838.                                     : singular($this->table).'_id';
  839.  
  840.                 if (in_array($relationship, $this->with))
  841.                 {
  842.                     $this->load->model($options['model']);
  843.                     $_model = explode('/', $options['model']);
  844.                     $_model = end($_model);
  845.                     if (is_array($row))
  846.                     {
  847.                         $row[$relationship] = $this->{$_model}->find_by(array($options['foreign'] => $row[$options['local']]));
  848.                     }
  849.                     else
  850.                     {
  851.                         $row->$relationship = $this->{$_model}->find_by(array($options['foreign'] => $row->{$options['local']}));
  852.                     }
  853.                 }
  854.             }
  855.         }
  856.  
  857.         // Loop through has_many in order to
  858.         // get data from the related table
  859.         if ( ! empty($this->has_many) and is_array($this->has_many))
  860.         {
  861.             foreach ($this->has_many as $key => $value)
  862.             {
  863.                 $options = array();
  864.  
  865.                 if (is_string($value))
  866.                 {
  867.                     $relationship = $value;
  868.                     $options['model'] = isset($options['model'])
  869.                                         ? $options['model']
  870.                                         : plural($value).'_model';
  871.                 }
  872.                 else
  873.                 {
  874.                     $relationship = $key;
  875.                     $options      = $value;
  876.                 }
  877.                 $options['local'] = isset($options['local'])
  878.                                     ? $options['local']
  879.                                     : $this->primary_key;
  880.                 $options['foreign'] = isset($options['foreign'])
  881.                                     ? $options['foreign']
  882.                                     : singular($this->table).'_id';
  883.  
  884.                 if (in_array($relationship, $this->with))
  885.                 {
  886.                     $this->load->model($options['model']);
  887.                     $_model = explode('/', $options['model']);
  888.                     $_model = end($_model);
  889.                     if (is_array($row))
  890.                     {
  891.                         $row[$relationship] = $this->{$_model}->find_many(array($options['foreign'] => $row->{$options['local']}));
  892.                     }
  893.                     else
  894.                     {
  895.                         $row->$relationship = $this->{$_model}->find_many(array($options['foreign'] => $row->{$options['local']}));
  896.                     }
  897.                 }
  898.             }
  899.         }
  900.         return $row;
  901.     }
  902.  
  903. }
  904.  
  905. /* End of file MY_Model.php */
  906. /* Location: ./application/core/MY_Model.php */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement