CodeIgniter Forums
Codeigniter 4 V 4.5.1 $this->db problem - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Codeigniter 4 V 4.5.1 $this->db problem (/showthread.php?tid=90882)

Pages: 1 2


RE: Codeigniter 4 V 4.5.1 $this->db problem - demyr - 05-17-2024

Just $db->table, without $this

PHP Code:
public function get_all_items(){
        $db      = \Config\Database::connect();
        $builder $db->table('items');
        $query $builder->select('*')
                 ->get();

                return $query->getResult();
    }
    

    
public function fetch_single_item($item_id){
        $db      = \Config\Database::connect();
        $builder $db->table('items');
        $query $builder->select('*')
                ->where('item_id'$item_id)
                ->get();

              return $query->getRow();
    



That will work


RE: Codeigniter 4 V 4.5.1 $this->db problem - serialkiller - 05-17-2024

Thanks, but I need to have the same instance in all the methods of the class, both to avoid having to declare it in each method and because when I make transactions I often call other methods from the method that manages the transaction so the connection must be the same


RE: Codeigniter 4 V 4.5.1 $this->db problem - demyr - 05-17-2024

Then we can get benefit of protected

Code:
    protected $table = 'items';
    protected $primaryKey = 'item_id';
    protected $allowedFields = ['field1', 'field2', 'field3'];

Then:

PHP Code:
public function get_all_items()
    {
        return $this->findAll(); 
    }

    
    
public function fetch_single_item($item_id)
    {
        return $this->where('item_id'$item_id)
                    ->first(); 
    



Is this what you are looking for?