CodeIgniter Forums

Full Version: Query builder question (CI 4 newbie)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there
I started making my first steps with CI4 after years of experience with CI. Now I'm struggling with something that worked fine with query builder prior to CI4.
Here are two functions of a basic model:
PHP Code:
public function getThread($id$field NULL) {

$query $this->db->table('threads')

$thread $query->getRow();

 if (
$thread == FALSE) {

    return FALSE;

$thread->posts $this->basicModel->getPostsByThread($thread->id);

 if (
is_null($field)) {

    return $thread;

 else {

    return $thread->$field;

 public function 
getPostsByThread($thread_id) {

$query $this->db->table('posts')


So, when calling function getThread() CI4 return the following error caused by the line $thread->posts = …:

Quote:CodeIgniter\Database\Exceptions\DatabaseException #8
You must set the database table to be used with your query.

I guess I have to rethink using query builder. Maybe you can give me a hint.
PHP Code:
$db      = \Config\Database::connect();
$builder $db->table('users'); 
Thanks for your answer.

Database connection is done automatically when extending the model with Model class, right?

What's the difference between

PHP Code:
$builder $db->table('users'

PHP Code:
$query $this->db->table('users')… 
$thread->posts = $this->basicModel->getPostsByThread($thread->id);
shoud be only this
$thread->posts = $this->getPostsByThread($thread->id); // why need basicModel ?? if u can call direct

same, since instance is shared.

1) you need to get the instance first , $db = db_connect();

2) instance from parent class (model) , $this->db;
Ah, now it's working!

$this->basicModel->… was wrong. It must be $this->… directly, as you mentioned.