ivantcholakov/codeigniter-base-model

after create

Closed this issue · 4 comments

hi

after create returns only the id or can i access the inserted data ?

Yes, it returns the id, this is the intention.

Immediately after the creation you already have data in memory. But, yes, you may need to retrieve your new record immediately (to get fresh data in memory), especially when some observers are active (for example, if you have generated fields created_at, updated_at and you want to get htese values immediately). The id is what you need. In this case, after create use the method get().

var_dump($data);
$id = $this->some_model->insert($data);
$data = $this->some_model->get($id);
var_dump($data);

no i was referring to the function inside the model

<?php defined('BASEPATH') or exit('No direct script access allowed');

class Test_m extends Core_Model
{
  public $_table = 'tests';
  public $primary_key = 'test_id';

  protected $return_type = 'array';

  public $after_create = array('test_after_create');

  protected function test_after_create($customer)
  {
       here customer is the id i asked if i can access the inserted data or i have to retrive it 
  }
}

I see, you are talking about the 'after_create' observer.

The logic about this observer is the same as it is in the original MY_Model project. I think, it is correct, let me try to explain why.

You may have at the same model 'before_create' and 'after_create' observers. In 'before_create' some field value may be added or modified. This is why the data in memory is not actual anymore. Data (if it is needed) for the observer 'after_create' should be taken from the just created database record. And for that the only passed parameter 'insert_id' is enough.

<?php defined('BASEPATH') or exit('No direct script access allowed');

class Test_m extends Core_Model
{
  public $_table = 'tests';
  public $primary_key = 'test_id';

  protected $return_type = 'array';

  public $after_create = array('test_after_create');

  protected function test_after_create($insert_id)
  {
       // here customer is the id i asked if i can access the inserted data or i have to retrive it

        $data = $this->get($insert_id);

        // Or if for some reason you want to avoid triggering here
        // the observers 'before_get' and 'after_get' you may use the
        // query builder directly, something like this:
        // $data = $this->_database->get_where($this->_table, array($this->primary_key => $insert_id), 1)->row_array();

        // Do something using the retrieved $data.
  }
}

ok thanks for your help