Search code examples
phpquery-buildercodeigniter-4

Call to undefined method CodeIgniter\Database\MySQLi\Connection::like()


I have i like query in my model but it doesn't work Model:

<?php namespace App\Models;

use CodeIgniter\Model;

class SearchModel extends Model
{
    protected $table      = 'sport_tbl';
    protected $primaryKey = 'id';
    protected $returnType     = 'array';
  
    public function search($word)
    {   
        $this->db->like('title', $word);
        $res = $this->db->get('sport_tbl')->result_array();
        return $res;
    }
}

Controller:

<?php namespace App\Controllers\api;
use App\Controllers\BaseController;
use App\Models\SearchModel;

class Search extends BaseController
{
    public function index()
    {
        $searchModel = new SearchModel(); 
     
        $data['allnews'] = $searchModel->search('test');

        return view('welcome_message', $data);
    }
}

And this is error: Call to undefined method CodeIgniter\Database\MySQLi\Connection::like()


Solution

  • You are basically using the old query builder style from Codeigniter 3 instead of Codeigniter 4.

    In Codeigniter 4 your code should look like this.

    <?php namespace App\Models;
    
    use CodeIgniter\Model;
    
    class SearchModel extends Model
    {
        protected $table      = 'sport_tbl';
        protected $primaryKey = 'id';
        protected $returnType = 'array';
      
        public function search($word)
        {   
            $db = \Config\Database::connect();
            $builder = $db->table('sport_tbl');
            $builder->like('title', $word);
            return $builder->get()->getResultArray();
        }
    }
    

    In this case your controller should be just the same.

    However there's another way of doing the same without creating a new database object and using the same one that is being automatically created for you.

    <?php namespace App\Models;
    
    use CodeIgniter\Model;
    
    class SearchModel extends Model
    {
        protected $table      = 'sport_tbl';
        protected $primaryKey = 'id';
        protected $returnType = 'array';
      
        public function search($word)
        {   
            $this->like('title', $word);
            return $builder->get()->getResultArray();
        }
    }
    

    In this case your controller should be a bit different:

    <?php namespace App\Controllers\api;
    use App\Controllers\BaseController;
    use App\Models\SearchModel;
    
    class Search extends BaseController
    {
        public function index()
        {
            $searchModel = new SearchModel(); 
         
            $data['allnews'] = $searchModel->search('test')->getAll();
    
            return view('welcome_message', $data);
        }
    }
    

    The second version of the code is actually better because that way your can have as many functions you want in your model and then just call them in a chain statement always returning $this.