php - 在一对多关系中获取字符串值而不是外部 id

标签 php html mysql pdo

我有一个查询将显示与其他表相关的表的字段/值。使用 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/

相关文章:

mysql - sql NOW() 并返回用户实际时区?

php - 将字段数据处理到mysql数据库的好方法

html - div 不使用 clear 或 br 分隔行

php - Mysql Views - 自动增量不工作(通过 Eloquent ORM)

html - 如何在IE中关闭图像边框

javascript - 在 Highcharts 中格式化数据标签

php - 如何进行查询以找到字符串中的特定文本并抓取其旁边的部分?

php - 类构造函数

php - 根据sql表编号更改单元格的背景颜色

php - 使用 mysql 中另一个表中的相似数据更新新数据库表的语法