在PHP中获取不带别名的SQL联接语句

问题描述 投票:0回答:1

按照我的代码:

$list = $pdo->prepare("SELECT * FROM table_a INNER JOIN table_b ON table_a.id = table_b.blabla_id");
$list_result = $list->execute();
while($element = $list->fetch()) {
//CONTENT
}

现在,我想用echo $element['table_a.id'];之类的内容来获取列-不起作用。我不想为每列写一个别名。有没有办法解决这个问题? :)

php sql join alias
1个回答
0
投票

一旦将呼叫更改为$list->fetch()即可将其固定为$list_result->fetch(),则可以使用$list_result->getColumnMeta($i)获取位置$i的列的元信息(包括表名),其中$i是结果集中索引为0的列。

然后,您可以遍历各列,检索其表名,并使用更新的键和原始数组中的值填充新数组:

while($element = $list->fetch()) {
    $a = []; // New array
    $i = 0;
    foreach ( $element as $k => $v ) { // For each element in the fetched row
        $meta = $list_result->getColumnMeta($i); // Get the meta info for column $i
        $a[ $meta->table . '.' . $k ] = $v; // E.g. $a[ 'table_a.id' ] = 'Foo'
        $i++; // Point to next column
    }
    $element = $a; // If you really need this variable name
}

现在您可以使用$element[ 'table_a.id' ]

您可能只想循环一次元信息就可以使我的示例更高效,因为每一列的表名在行与行之间都不会改变。

请参见https://www.php.net/manual/en/pdostatement.getcolumnmeta.php以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.