我有一个查询将显示与其他表相关的表的字段/值。使用 foreach 循环,我可以在 html 中显示这些字段/值。但我想显示 'foreign_name' 而不是'foreign_id'。
<?php foreach ($table_related as $table): ?>
<?php echo $table['id']; ?>
<?php echo $table['foreign_id']; ?>//the foreign key, it should be foreign_name
<?php echo $table['name'];?>
<?php endforeach; ?>
//classeManageService.php
function showAllServices()
{
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
$rowcount = $query->rowCount();
if($rowcount > 0)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
return $result;
}
//show_all.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$show_all_services = $init->showAllServices();
?>
'my_table' 有列 id、my_name、desc、foreign_id,'other_table' 有列 foreign_id、foreign_name、foreign_desc
我可以在 html 中显示所有这些值。但是如何显示其他字段而不是其他表中的 id?我必须更改查询吗?有什么想法吗?
最佳答案
您必须使用 JOIN
进行查询:
由于您没有提供其他表名,请考虑使用otherTable
,将service_id
作为外键。
查询示例:
$query = $this->link->query("SELECT * FROM services s, otherTable o WHERE s.id = o.service_id ORDER BY s.id DESC");
现在在结果集中,您还将拥有 otherTable
的所有字段,您可以从中获得所需的名称。
关于php - 在一对多关系中获取字符串值而不是外部 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27192709/