Skip to content

Commit 12d16ea

Browse files
authored
完善Query的column方法以支持指定表别名 (#712)
* 完善Query的column方法以支持指定表别名 * 索引列兼容别名 * 增加单元测试:通过指定表别名获取字段列数据 * 修正格式
1 parent 7cacaad commit 12d16ea

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

src/Db/Query/Query.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1293,9 +1293,21 @@ public function column($fields, ?string $key = null): array
12931293
->select();
12941294

12951295
$records = $result->getStatementRecords();
1296+
1297+
if (\is_string($key) && strpos($key, '.'))
1298+
{
1299+
[, $key] = explode('.', $key);
1300+
}
1301+
12961302
if (1 === \count($rawFields))
12971303
{
1298-
return array_column($records, $rawFields[0], $key);
1304+
$column = $rawFields[0];
1305+
if (strpos($column, '.'))
1306+
{
1307+
[, $column] = explode('.', $column);
1308+
}
1309+
1310+
return array_column($records, $column, $key);
12991311
}
13001312
else
13011313
{

tests/unit/Component/Tests/Db/DbBaseTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,38 @@ public function testColumn(array $args): void
674674
$this->assertEquals(array_column_ex($origin, ['title', 'content', 'time', 'id'], 'id'), $data);
675675
}
676676

677+
/**
678+
* @depends testBatchInsert
679+
*/
680+
public function testAliasColumn(array $args): void
681+
{
682+
$origin = $args['origin'];
683+
684+
$data = Db::query($this->poolName)
685+
->table('tb_article', 't')
686+
->column('t.content');
687+
688+
$this->assertEquals(array_column($origin, 'content'), $data);
689+
690+
$data = Db::query($this->poolName)
691+
->table('tb_article', 't')
692+
->column('t.content', 't.id');
693+
694+
$this->assertEquals(array_column($origin, 'content', 'id'), $data);
695+
696+
$data = Db::query($this->poolName)
697+
->table('tb_article', 't')
698+
->column(['t.id', 't.content'], 't.id');
699+
700+
$this->assertEquals(array_column_ex($origin, ['id', 'content'], 'id'), $data);
701+
702+
$data = Db::query($this->poolName)
703+
->table('tb_article', 't')
704+
->column(['t.title', 't.content', 't.time'], 't.id');
705+
706+
$this->assertEquals(array_column_ex($origin, ['title', 'content', 'time', 'id'], 'id'), $data);
707+
}
708+
677709
/**
678710
* @depends testInsert
679711
*/

0 commit comments

Comments
 (0)