2

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()

marcogmonteiro
  • 2,061
  • 1
  • 17
  • 26
Farid
  • 158
  • 1
  • 2
  • 13
  • You cant dirrectly use query on database. You need to use Query builder. Refer to the following link : https://codeigniter4.github.io/userguide/database/query_builder.html?highlight=query%20builder – Dhaval Chheda Oct 19 '20 at 17:24

1 Answers1

2

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.

marcogmonteiro
  • 2,061
  • 1
  • 17
  • 26