在 Codeigniter 4 中,你如何在 $this->db->table('table_name') 中编写/调用 2 个表



你好,我现在有 2 个表,我想调用它,用于编辑(CRUD 的一部分) 表:

  1. table_a
  2. table_b

我在 YouTube 中找到了如何从 2 个表格更新/编辑,我需要调用表格的机器人。 这是模型的代码

public function  edit_this($ID_A)
{
return $this->db->table('table_a', '*i don't know how to insert the 2nd table')->where('ID_A', $ID_A)->get()->getRowArray();
}

这是控制器

public function this_edit($ID_A)
{
$data = [
'title' => 'Admin',
'navbartitel' => 'You know this',
'alledit' => $this->theModel->edit_this($ID_A),
'validation' => ConfigServices::validation()
];
return view('this/all/edit', $data);
}

它可以工作,但我只能访问tabel_a,但我都需要它们,以便我可以从数据库中显示我在编辑表单中编写的内容

有人可以帮忙吗?谢谢

$this->db->table(...)返回QueryBuilder的一个实例,并且很乐意接受一个逗号分隔的表字符串("table1, table2..."),甚至一个数组(['table1', 'table2'...]),作为它的第一个参数。您两者都不执行,而是传递多个参数。

调用table()时,在创建特定于数据库的 Builder 类期间使用在第一个参数中传递的值:

public function table($tableName)
{
if (empty($tableName))
{
throw new DatabaseException('You must set the database table to be used with your query.');
}
$className = str_replace('Connection', 'Builder', get_class($this));
return new $className($tableName, $this);
}

特定于数据库的 Builder 类没有自己的构造函数,因此回退到 BaseBuilder 中定义的__construct,它扩展了:

public function __construct($tableName, ConnectionInterface &$db, array $options = null)
{
if (empty($tableName))
{
throw new DatabaseException('A table must be specified when creating a new Query Builder.');
}
$this->db = $db;
$this->from($tableName);
...

为了简洁起见,我截断了它,因为重要的部分是对$this->from的调用,这是最终处理多个表的方式:

public function from($from, bool $overwrite = false)
{
if ($overwrite === true)
{
$this->QBFrom = [];
$this->db->setAliasedTables([]);
}
foreach ((array) $from as $val)
{
if (strpos($val, ',') !== false)
{
foreach (explode(',', $val) as $v)
{
$v = trim($v);
$this->trackAliases($v);
$this->QBFrom[] = $v = $this->db->protectIdentifiers($v, true, null, false);
}
}
else
{
$val = trim($val);
// Extract any aliases that might exist. We use this information
// in the protectIdentifiers to know whether to add a table prefix
$this->trackAliases($val);
$this->QBFrom[] = $this->db->protectIdentifiers($val, true, null, false);
}
}
return $this;
}

最新更新