Welcome Guest, Not a member yet? Register   Sign In
Something wrong in my model
#1

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
Reply
#2

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
Reply
#3

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;

Reply
#4

Thanks for this trick I'll test it soon  Smile
Reply




Theme © iAndrew 2016 - Forum software by © MyBB