【问题标题】:How to use Multiple Tables in Codeigniter 4如何在 Codeigniter 4 中使用多个表
【发布时间】:2020-09-20 16:36:00
【问题描述】:

到目前为止,我一直在使用 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();

  }


 }

由于某种原因,整个事情似乎没有成功。

有人可以帮我吗?

【问题讨论】:

  • 你遇到了什么错误?
  • 没有错误,但似乎 CI 使用了两个表(main_table 和 another_table)。我只想使用第二个。
  • 在 getMainImage 中尝试设置 $this->table="another_table" 比不需要 from,但问题是如果你在这之后调用 getAll 我会查询 another_table 因为表名已经设置。
  • 不幸的是,这个 CI 只查看“main_table”而完全忽略了“another_table”......

标签: codeigniter model


【解决方案1】:

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

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

【讨论】:

  • 你确定吗?这会产生“调用未定义的方法 CodeIgniter\Database\MySQLi\Builder::table()”错误
  • @Tom 我编辑了答案以将完整的功能结构添加到您需要的内容中。
  • @marcogmonteiro 你是什么意思?有了这里给出的答案,我仍然收到错误“调用未定义的方法 CodeIgniter\Database\MySQLi\Builder::table()”
  • @marcogmonteiro Thx,但现在是“调用未定义的方法 CodeIgniter\Database\MySQLi\Builder::findAll()”
  • @Tom 现在应该没事了。
猜你喜欢
  • 2015-04-08
  • 2013-03-23
  • 2020-11-13
  • 2020-05-23
  • 1970-01-01
  • 2014-09-07
  • 2021-07-15
  • 1970-01-01
  • 2020-06-07
相关资源
最近更新 更多