diff --git a/src/ORM/Table.php b/src/ORM/Table.php index 1f8b0eb7584..7754746b0e2 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -1231,10 +1231,17 @@ protected function _processSave($entity, $options) { * @param array $data The actual data that needs to be saved * @return \Cake\Datasource\EntityInterface|bool * @throws \RuntimeException if not all the primary keys where supplied or could - * be generated when the table has composite primary keys + * be generated when the table has composite primary keys. Or when the table has no primary key. */ protected function _insert($entity, $data) { $primary = (array)$this->primaryKey(); + if (empty($primary)) { + $msg = sprintf( + 'Cannot insert row in "%s", it has no primary key.', + $this->table() + ); + throw new \RuntimeException($msg); + } $keys = array_fill(0, count($primary), null); $id = (array)$this->_newId($primary) + $keys; $primary = array_combine($primary, $id); diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index f37c3e3788a..f48d3670e98 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -1364,6 +1364,25 @@ public function testAfterSaveNotCalled() { $this->assertFalse($called); } +/** + * Test that you cannot save rows without a primary key. + * + * @group save + * @expectedException \RuntimeException + * @expectedExceptionMessage Cannot insert row in "users", it has no primary key + * @return void + */ + public function testSaveNewErrorOnNoPrimaryKey() { + $entity = new \Cake\ORM\Entity(); + $table = TableRegistry::get('users', [ + 'schema' => [ + 'id' => ['type' => 'integer'], + 'username' => ['type' => 'string'], + ] + ]); + $table->save($entity); + } + /** * Tests that save is wrapped around a transaction *