CodeIgniter Forums
Query builder question (CI 4 newbie) - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Query builder question (CI 4 newbie) (/showthread.php?tid=79788)



Query builder question (CI 4 newbie) - bastian - 07-27-2021

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')
              ->where('id'$id)
              ->get();

 
$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')
              ->where('thread_id'$thread_id)
              ->orderBy('date')
              ->get();

 return 
$query->getResult();
 } 

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.


RE: Query builder question (CI 4 newbie) - InsiteFX - 07-27-2021

PHP Code:
$db      = \Config\Database::connect();
$builder $db->table('users'); 



RE: Query builder question (CI 4 newbie) - bastian - 07-27-2021

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'

and
PHP Code:
$query $this->db->table('users')… 



RE: Query builder question (CI 4 newbie) - ikesela - 07-27-2021

YOUR CODE ABOVE:
$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

SECOND:
same, since instance is shared.

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

2) instance from parent class (model) , $this->db;


RE: Query builder question (CI 4 newbie) - bastian - 07-27-2021

Ah, now it's working!

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