How to use Multiple Tables in Codeigniter 4

Viewed 6462

I have worked with CI 3 so far and would like to address several database tables separately (no joins) in a new model (in CI 4).

<?php namespace App\Models;

use CodeIgniter\Model;


class MyModel extends Model {

  protected $table = 'main_table';

  public function getAll($uid = false) {

    return $this->where(['hidden' => '0'])
                ->where(['deleted' => '0'])
                ->findAll();

  }


  public function getMainImage($pid) {

    return $this->from('another_table')
                ->where(['pid' => $pid])
                ->findAll();

  }


 }

For some reason the whole thing doesn't seem to work out.

Can someone help me?

1 Answers

You need to instanciate the db connection again and assign the second table to that variable inside the function, like this:

public function getMainImage($pid) {
    $db = \Config\Database::connect();
    $builder = $db->table('secondary_table');
    
    return $builder->where(['pid' => $pid])
         ->get()->getResult();
}

More information on how to use the query builder here: https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder

Related