如何在 Codeigniter 4 中使用多个表

问题描述 投票:0回答:2

到目前为止,我一直在使用 CI 3,并且希望在新模型(在 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();

  }


 }

出于某种原因,整件事似乎并没有成功。

有人可以帮助我吗?

codeigniter model
2个回答
3
投票

您需要再次实例化数据库连接并将第二个表分配给函数内的该变量,如下所示:

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

有关如何使用查询生成器的更多信息,请参见此处: https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder


0
投票

我有另一种方法可以利用 CI4 中的

Model->db
属性来使用多个表。我会将
another_table
构建器分配给所需函数中的受保护属性(我可以选择使用
Model.initialize()
在加载时撤销)(在本例中为
getMainImage

<?php

class MyModel extends Model
{

  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();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.