查询语言.columns

Testing Is Documentation

tests/Database/Query/ColumnsTest.php查询语言.columns - 图1

Uses

  1. <?php
  2. use Leevel\Database\Condition;
  3. use Tests\Database\DatabaseTestCase as TestCase;

Columns 添加字段

字段条件用法和 table 中的字段用法一致,详情可以查看《查询语言.table》。

  1. public function testBaseUse(): void
  2. {
  3. $connect = $this->createDatabaseConnectMock();
  4. $sql = <<<'eot'
  5. [
  6. "SELECT `test_query`.*,`test_query`.`id`,`test_query`.`name`,`test_query`.`value` FROM `test_query`",
  7. [],
  8. false
  9. ]
  10. eot;
  11. $this->assertSame(
  12. $sql,
  13. $this->varJson(
  14. $connect
  15. ->table('test_query')
  16. ->columns('id')
  17. ->columns('name,value')
  18. ->findAll(true)
  19. )
  20. );
  21. }

SetColumns 设置字段

清空原有字段,然后添加新的字段。

  1. public function testSetColumns(): void
  2. {
  3. $connect = $this->createDatabaseConnectMock();
  4. $sql = <<<'eot'
  5. [
  6. "SELECT `test_query`.`remark` FROM `test_query`",
  7. [],
  8. false
  9. ]
  10. eot;
  11. $this->assertSame(
  12. $sql,
  13. $this->varJson(
  14. $connect
  15. ->table('test_query')
  16. ->columns('id')
  17. ->columns('name,value')
  18. ->setColumns('remark')
  19. ->findAll(true)
  20. )
  21. );
  22. }

Columns 字段支持表达式

  1. public function testColumnsExpressionForSelectString(): void
  2. {
  3. $connect = $this->createDatabaseConnectMock();
  4. $sql = <<<'eot'
  5. [
  6. [
  7. "SELECT 'foo'",
  8. [],
  9. false
  10. ]
  11. ]
  12. eot;
  13. $this->assertSame(
  14. $sql,
  15. $this->varJson(
  16. [
  17. $connect
  18. ->columns(Condition::raw("'foo'"))
  19. ->findAll(true),
  20. ]
  21. )
  22. );
  23. }

Columns 字段在连表中的查询

  1. public function testSetColumnsWithTableName(): void
  2. {
  3. $connect = $this->createDatabaseConnectMock();
  4. $sql = <<<'eot'
  5. [
  6. "SELECT `test_query`.`name`,`test_query`.`value`,`test_query_subsql`.`name`,`test_query_subsql`.`value` FROM `test_query` INNER JOIN `test_query_subsql` ON `test_query_subsql`.`name` = `test_query`.`name`",
  7. [],
  8. false
  9. ]
  10. eot;
  11. $this->assertSame(
  12. $sql,
  13. $this->varJson(
  14. $connect
  15. ->table('test_query')
  16. ->setColumns('test_query.name,test_query.value')
  17. ->join('test_query_subsql', 'name,value', 'name', '=', Condition::raw('[test_query.name]'))
  18. ->findAll(true)
  19. )
  20. );
  21. }