Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Database/Table/Selection.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,26 @@ public function fetch()
}


/**
* Fetches single field.
* @param string|NULL
* @return mixed|FALSE
*/
public function fetchField($column = NULL)
{
if ($column) {
$this->select($column);
}

$row = $this->fetch();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about select($column) before fetch?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dg Makes sense, but shouldn't be then select added to fetchPairs too? And it will probably not work for int column key which is default for fetchField function.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ActiveRow supports indexed keys?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I see, it does not. So I can add select() as you proposed and make $column without default value. Or I can try to update ActiveRow to support indexed keys. What would you like reather?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ActiveRow should not support indexed keys. $column default value can be NULL to allow $table->select('xx')->fetchSingle() too.

if ($row) {
return $column ? $row[$column] : array_values($row->toArray())[0];
}

return FALSE;
}


/**
* @inheritDoc
*/
Expand Down
24 changes: 24 additions & 0 deletions tests/Database/Table/Selection.fetchField().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/**
* Test: Nette\Database\Table: Fetch field.
* @dataProvider? ../databases.ini
*/

use Tester\Assert;

require __DIR__ . '/../connect.inc.php'; // create $connection

Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverName}-nette_test1.sql");


test(function () use ($context) {
$title = $context->table('book')->where('id', 1)->fetchField('title'); // SELECT `title` FROM `book` WHERE `id` = 1
Assert::same('1001 tipu a triku pro PHP', $title);
});


test(function () use ($context) {
$title = $context->table('book')->where('id', 1)->select('title')->fetchField(); // SELECT `title` FROM `book` WHERE `id` = 1
Assert::same('1001 tipu a triku pro PHP', $title);
});