Skip to content

Commit 1a00d45

Browse files
committed
Fix Model::first() only use orderBy() when group by is not empty
1 parent 08dd1a5 commit 1a00d45

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

system/Model.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -472,8 +472,8 @@ public function first()
472472
}
473473

474474
// Some databases, like PostgreSQL, need order
475-
// information to consistently return correct results.
476-
if (empty($builder->QBOrderBy) && ! empty($this->primaryKey))
475+
// information to consistently return correct results when there is group by
476+
if (! empty($this->QBGroupBy) && empty($builder->QBOrderBy) && ! empty($this->primaryKey))
477477
{
478478
$builder->orderBy($this->table . '.' . $this->primaryKey, 'asc');
479479
}

tests/system/Database/Live/ModelTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,31 @@ public function testFirst()
251251

252252
//--------------------------------------------------------------------
253253

254+
public function testFirstWithoutGroupBy()
255+
{
256+
$model = new UserModel();
257+
258+
$user = $model->select('SUM(id) as total')
259+
->where('id >', 2)
260+
->first();
261+
$this->assertEquals(7, $user->total);
262+
}
263+
264+
//--------------------------------------------------------------------
265+
266+
public function testFirstWithGroupBy()
267+
{
268+
$model = new UserModel();
269+
270+
$user = $model->select('SUM(id) as total')
271+
->where('id >', 2)
272+
->groupBy('id')
273+
->first();
274+
$this->assertEquals(3, $user->total);
275+
}
276+
277+
//--------------------------------------------------------------------
278+
254279
public function testFirstRespectsSoftDeletes()
255280
{
256281
$this->db->table('user')

0 commit comments

Comments
 (0)