在另一个 table 中显示一个 table 的值 (Codeigniter 4)

Show value of one table in other table (Codeigniter 4)

我有两个表:

表 1:

ID 姓名 电子邮件 profile_id

表 2:

id profile_name

我在视图中使用 foreach 循环向网站上的用户显示 table,但在该视图中我希望 profile_id 显示相应的 profile_name 来自 table2 而不是 ID。

我想我应该使用 join(),但我不知道如何使用它。如果需要,我可以提供我的代码,但我认为不需要。

有什么帮助吗?

在查看 codeigniter 4 创建查询的方法之前,花点时间了解连接背后的基本 SQL。联接允许您合并来自多个 table 的结果。您需要具体说明要从哪个 table 中获取哪个值。在基本 SQL 中看起来像

SELECT table1.something, table2.somethingElse 
FROM table1
JOIN table2
ON table1.id = table2.referenceID

关键是ON关键字。它在 2 table 之间建立了 link。有时您的结果中会有相同的字段名称,例如 ID,因此您可以使用 AS like

更改查询中的字段名称
SELECT  
   *, table1.id AS table1_id, 
   table2.id AS table2_id 
FROM table1
JOIN table2
ON table1.id= table2.referenceID

此查询仍会从两个数据库中获取 id 列,但还会获取新的临时字段,以便我们区分结果。

codeigniter 4中你只需使用他们的方法

$builder = $db->table('table1');
$builder->select('table1.*, table2.profile_name');
$builder->join('table2', 'table1.profile_id = table2.id');
$query = $builder->get();
foreach ($query->getResult() as $row)
{
    $users[]= $row;
}
echo view('myPage', array('users' => $users) );

这是联接的最基本的入门介绍。我鼓励你 learn more about them