Tom
Tom

Reputation: 79

How to use Multiple Tables in Codeigniter 4

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?

Upvotes: 3

Views: 9292

Answers (2)

Vishal Kumar Sahu
Vishal Kumar Sahu

Reputation: 1396

I have alternate approach to consume multiple tables in CI4 exploiting Model->db property. I would assign another_table builder to protected property (optionally I can use Model.initialize() to revoke on load) in the desired function (in this case getMainImage)

<?php

class MyModel extends Model
{
  protected $DBGroup = 'TBGroup';
  protected $table = 'main_table';
  protected $table_another_table = null;

  // optional preload
  function initialize()
  {
    $this->table_another_table = $this->db->table('another_table');
  }

  public function getAll($uid = false)
  {

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


  public function getMainImage($pid)
  {
    // Optionally preload in initialize method
    $this->table_another_table = $this->db->table('another_table');
    return $this->table_secondary
      ->where(['pid' => $pid])
      ->findAll();
  }
}

Model->DBGroup property is important in this case.

Upvotes: 0

Emerson Nunes
Emerson Nunes

Reputation: 456

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

Upvotes: 3

Related Questions