CodeIgniter Forums
Why - You must set the database table to be used with your query. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Why - You must set the database table to be used with your query. (/showthread.php?tid=92279)



Why - You must set the database table to be used with your query. - 4usol - 01-05-2025

Hi, I wondering about getting this error " You must set the database table to be used with your query."


The marked line is this 
Code:
$var=$this->MyModel ->my_function($vars,$id);


I do that inside a library. The parts of the model are
Code:
namespace App\Models;
use CodeIgniter\Model;

class MyModel extends Model
{
    protected $DB;
     

    #### INIT YOUR MODEL ####
    protected function initialize()
    {
        $this->DB = db_connect('DB');   
        $this->DBA = db_connect('DBA');   
    }

public function my_function($fields,$id)
    {
       
        $qry=$this->DB->table('my_db_table');            //here i define the table, thats why i dont  understand the errormessage!?

        //Select
        if(empty($fields) || in_array('*',$fields)){ $qry->select('*'); }else{ $qry->select($fields); }
       
        //Where
        $qry->Where(['id' => $id]);
     
        //Get the results as RowArray
        $res= $qry->get()->getResultArray();

        //return as array or array of arrays
        if(count($res)>1){ return $res; }else{ return $res[0]; }         
    }

}

may i'm blind to see the missing thing...


RE: Why - You must set the database table to be used with your query. - captain-sensible - 01-05-2025

Code:
<?php

namespace App\Models;

use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;
class BlogModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'blog';
    protected $primaryKey       = 'Id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
       protected $allowedFields = ['title','article','image','slug','date','font'];
    // Dates
    protected $useTimestamps = false;

if you extend CI4 model , you set field in class definition


RE: Why - You must set the database table to be used with your query. - 4usol - 01-05-2025

Is it a MUST to define all these "protected ...." settings,
i dont wont to work with the  built-in CRUD methods, so i guess that i dont need to define it!?

I have figure out that the problem comes from another direction, a name of a called function was wrong, if i corret this, the error message (i'm confused about the kind of messag) go away. Now the model works well, without setup the datas on top of the modell.