基于外键获取另一列的值


Get value of another column based on foreign key

我正在web应用程序中为管理员显示视图中表中的所有数据。

SQL看起来像这样:

$organizations = $db->query("
    SELECT id, organization_name, owner_id
    FROM organizations
    ORDER BY created_on DESC
  ")->fetchALL(PDO::FETCH_ASSOC);

我正在处理的观点如下:

<?php foreach($organizations as $organization): ?>
   <tr>
     <td><?php echo e($organization['organization_name']); ?></td>
     <td><?php echo e($organization['owner_id']); ?></td>
   </tr>
<?php endforeach; ?>

这完全符合预期,但实际上并不是我想要显示的owner_id(一个int和users表的主键)

这将生成一个包含SQL语句中所有值的表,特别是它将向视图呈现owner_id,该视图是与我的users表相关的外键。

我想做的是实际显示属于owner_id的所有者的name,而不是仅仅显示id(即..32)。如何根据引用的外键user_id显示users表中用户的关联name

您需要使用JOIN来链接这两个表。下面的示例链接owner_id上的两个表,并在结果中包含user_name。如果两个表中都存在任何列名,则需要在SELECT中使用别名。

-- use alias and include user_name
SELECT o.id, o.organization_name, u.user_id, u.user_name 
-- alias the table as "o"
FROM organizations o 
-- alias the table as "u"
JOIN users u 
    -- link the tables here on owner_id
    ON o.owner_id = u.user_id 
ORDER BY o.created_on DESC

然后,您可以在PHP中输出user_name列的值,如下所示:

<td><?php echo e($organization['user_name']); ?></td>

您可以使用JOIN。

$organizations = $db->query("
    SELECT organizations.id, organizations.organization_name, 
    users.user_name
    FROM organizations
    JOIN users ON organizations.owner_id = users.user_id
    ORDER BY organizations.created_on DESC
  ")->fetchALL(PDO::FETCH_ASSOC);

然后在视图中,它可以用作

<?php foreach($organizations as $organization): ?>
   <tr>
     <td><?php echo e($organization['organization_name']); ?></td>
     <td><?php echo e($organization['user_name']); ?></td>
   </tr>
<?php endforeach; ?>