diff --git a/system/Model.php b/system/Model.php index 751adcb73191..d841d2874fd8 100644 --- a/system/Model.php +++ b/system/Model.php @@ -398,7 +398,7 @@ public function first() // Some databases, like PostgreSQL, need order // information to consistently return correct results. - if (empty($builder->QBOrderBy)) + if (empty($builder->QBOrderBy) && ! empty($this->primaryKey)) { $builder->orderBy($this->table . '.' . $this->primaryKey, 'asc'); } diff --git a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php index 3c84cbbdfd89..8d4a93a0da9c 100644 --- a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php +++ b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php @@ -85,6 +85,16 @@ public function up() ]); $this->forge->addKey('id', true); $this->forge->createTable('empty', true); + + //No Primary Key + $this->forge->addField([ + 'key' => [ + 'type' => 'VARCHAR', + 'constraint' => 40, + ], + 'value' => ['type' => 'TEXT'], + ]); + $this->forge->createTable('secondary', true); } //-------------------------------------------------------------------- @@ -95,6 +105,7 @@ public function down() $this->forge->dropTable('job'); $this->forge->dropTable('misc'); $this->forge->dropTable('empty'); + $this->forge->dropTable('secondary'); } //-------------------------------------------------------------------- diff --git a/tests/_support/Models/SecondaryModel.php b/tests/_support/Models/SecondaryModel.php new file mode 100644 index 000000000000..19d8228f5f1a --- /dev/null +++ b/tests/_support/Models/SecondaryModel.php @@ -0,0 +1,21 @@ +assertEquals(1, $user->id); } + public function testFirstWithNoPrimaryKey() + { + $model = new SecondaryModel(); + + $this->db->table('secondary')->insert([ + 'key' => 'foo', + 'value' => 'bar', + ]); + $this->db->table('secondary')->insert([ + 'key' => 'bar', + 'value' => 'baz', + ]); + + $record = $model->first(); + + $this->assertEquals(1, count($record)); + $this->assertEquals('foo', $record->key); + } + //-------------------------------------------------------------------- public function testSaveNewRecordObject()