Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Added rawValue to Database Query Builder (and Eloquent as wrapper) #44631

Merged
merged 1 commit into from
Oct 19, 2022
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
1 change: 1 addition & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ class Builder implements BuilderContract
'max',
'min',
'raw',
'rawValue',
'sum',
'toSql',
];
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2596,6 +2596,20 @@ public function value($column)
return count($result) > 0 ? reset($result) : null;
}

/**
* Get a single expression value from the first result of a query.
*
* @param string $expression
* @param array $bindings
* @return mixed
*/
public function rawValue(string $expression, array $bindings = [])
{
if ($result = $this->selectRaw($expression, $bindings)->take(1)->first()) {
return reset($result);
}
}

/**
* Get a single column's value from the first result of a query if it's the sole matching record.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2464,6 +2464,15 @@ public function testValueMethodReturnsSingleColumn()
$this->assertSame('bar', $results);
}

public function testRawValueMethodReturnsSingleColumn()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->once()->with('select UPPER("foo") from "users" where "id" = ? limit 1', [1], true)->andReturn([['UPPER("foo")' => 'BAR']]);
$builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['UPPER("foo")' => 'BAR']])->andReturn([['UPPER("foo")' => 'BAR']]);
$results = $builder->from('users')->where('id', '=', 1)->rawValue('UPPER("foo")');
$this->assertSame('BAR', $results);
}

public function testAggregateFunctions()
{
$builder = $this->getBuilder();
Expand Down