@@ -52,18 +52,35 @@ protected function selectColumnToQuery(array &$selectAsColumns, SelectWriter $se
5252 {
5353 \array_walk (
5454 $ selectAsColumns ,
55- function (mixed &$ column ) use ($ selectWriter ): void {
56- $ keys = \array_keys ($ column );
57- $ key = \array_pop ($ keys );
58-
59- $ values = \array_values ($ column );
60- /** @var Column|string $value */
61- $ value = $ values [0 ];
62-
63- if (\is_numeric ($ key ) && $ value instanceof Column) {
64- $ key = $ this ->writer ->writeTableName ($ value ->getTable ());
55+ function (mixed &$ columnData ) use ($ selectWriter ): void {
56+ // $columnData is expected to be an array like ['alias_or_index' => Select_object_or_string]
57+ $ keys = \array_keys ($ columnData );
58+ $ originalKey = \array_pop ($ keys ); // Get the alias or numeric index
59+
60+ $ values = \array_values ($ columnData );
61+ $ content = $ values [0 ]; // This is the Select object or column name string
62+
63+ $ aliasToUse = $ originalKey ; // Default to original key
64+
65+ if (\is_numeric ($ originalKey ) && $ content instanceof \NilPortugues \Sql \QueryBuilder \Manipulation \Select) {
66+ /** @var \NilPortugues\Sql\QueryBuilder\Syntax\Table|null $firstTable */
67+ $ firstTable = $ content ->getTable (); // Get the main table of the subquery
68+
69+ if ($ firstTable ) { // Check if a table is actually set
70+ $ derivedAlias = $ firstTable ->getAlias ();
71+ if (null === $ derivedAlias || $ derivedAlias === '' ) {
72+ $ derivedAlias = $ firstTable ->getName ();
73+ }
74+
75+ if ($ derivedAlias && $ derivedAlias !== '' ) {
76+ $ aliasToUse = $ derivedAlias ;
77+ }
78+ }
79+ // If no table or no alias/name, $aliasToUse remains $originalKey (numeric string)
6580 }
66- $ column = $ selectWriter ->selectToColumn ((string )$ key , $ value );
81+ // Important: ensure $aliasToUse is a string for selectToColumn
82+ // The variable name for the modified element in array_walk is $columnData itself
83+ $ columnData = $ selectWriter ->selectToColumn ((string )$ aliasToUse , $ content );
6784 }
6885 );
6986
@@ -117,7 +134,7 @@ public function writeFuncAsColumns(Select $select): array
117134 public function writeColumnWithAlias (Column $ column ): string
118135 {
119136 $ alias = $ column ->getAlias ();
120- if ($ alias !== null && $ alias !== '' && ! $ column ->isAll ()) {
137+ if ($ alias !== null && ! $ column ->isAll ()) { // Removed $alias !== ''
121138 return $ this ->writeColumn ($ column ).' AS ' .$ this ->writer ->writeColumnAlias ($ alias );
122139 }
123140
0 commit comments