CodeIgniter Forums
Something wrong in my model - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Something wrong in my model (/showthread.php?tid=64550)



Something wrong in my model - brian85 - 03-03-2016

Hi, I'm working in CI 2.2

I'm having trouble with my model :

PHP Code:
class Stages_model extends CI_Model {

 
   private $id_stages;

public function 
set_sessions() {
 
       $array_search_sessions = array('id_stages' => $this->id_stages);
 
       $this->load->model('sessions_model');
 
       $this->sessions find_sessions_by($array_search_sessions);
 
       //$this->sessions = $sessions;
 
   }

public function 
getId_stages() {
 
       return $this->id_stages;
 
   }

public function 
find($value) {

 
       $this->load->database();
 
       $q $this->db->get_where("stages", array("id_stages" => $value), 1);

 
       if ($q->num_rows() == 1) {
 
           $row $q->result();
 
           foreach ($row[0] as $key => $field) {
 
               $this->$key $field;
 
           }
 
          
            $this
->set_sessions();
 
       }
 
       //return $row;
 
       return $this;
 
   }



and when I'm calling the function find in a loop in my controller like that :

PHP Code:
foreach ($array_selection as $key_sel => $idStage) {
 
    $ce_stage $this->stages_model->find($idStage);
 
    $data['stages'][] = $ce_stage;


The dump of $data['satges'] show the same result : the last value.Huh
It seems that returning the instance affects all values in the array, how is it possible ?  
How can I get in my array different instances of my model object in $data[''stages'] ?

Thanks for your help  Smile


[SOLVED]RE: Something wrong in my model - brian85 - 03-03-2016

I answer myself I've found the way here is my corrected model function find() :  
PHP Code:
public function find($value) {

 
       $this->load->database();
 
       $q $this->db->get_where("stages", array("id_stages" => $value), 1);
 
       $r $q->result(get_class($this))[0];
 
       $r->set_sessions(); // a private method to complete this object

 
       return $r;
 
   


Now it works perfectly !  Big Grin

I hope this could help

see you next time, I really enjoy CI my next project will use CI 3


RE: [SOLVED]RE: Something wrong in my model - pdthinh - 03-03-2016

I think you can use PHP clone keyword
PHP Code:
foreach ($array_selection as $key_sel => $idStage) {
 
    $ce_stage $this->stages_model->find($idStage);
 
    $data['stages'][] = clone $ce_stage;




RE: Something wrong in my model - brian85 - 03-04-2016

Thanks for this trick I'll test it soon  Smile