Welcome Guest, Not a member yet? Register   Sign In
Query builder question (CI 4 newbie)
#1

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.
Reply
#2

PHP Code:
$db      = \Config\Database::connect();
$builder $db->table('users'); 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

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')… 
Reply
#4

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;
Reply
#5

Ah, now it's working!

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




Theme © iAndrew 2016 - Forum software by © MyBB