Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Cannot delete record in database - A primary key must be defined in the model in order to perform the operation

Hello I'm checking if a record exists in database by calling $result = Model::findFirst(array of conditions)

if($result) - record exists and i want to do $result->delete() but phalcon shows a notice "A primary key must be defined in the model in order to perform the operation" and I have not primary key defined in that table or any other key. its just a simple table with 2 columns. Is it a bug or what am I doing wrong.



506
Accepted
answer

You should add an id column to your DB table and set it as Primary Key with Auto Increment. Won't affect your table structure and it's always better to update or delete rows with their primary key.

After you're done adding the column you can re-use the model command in the CLI webtools with the --force option and Phalcon will rebuild the model file with the new column as the primary key.



6.5k

ok I did what you suggested. I didnt want to add a column with a key because its kinda useless and from what i've heard indexes slow down a bit inserting (when many row in database) but I guess this micro optimalization is not worth having primary key set. thank you. But on the other hand I would like to know if there's another way.

edited May '14

Sometimes adding a primary key it's a overkill. Like in relational tables that get updated frequently, besides the indexing reducing the performance, the auto-increment value can reach the limit really fast.

Shame that isn't supported even throught PHQL, don't know if it's a PDO limitation but this sucks anyway.

I am migrating an application that was made in CodeIgniter for Phalcon. I could, without problems, delete the records from this table using a reference to another table (DELETE FROM TABLE1 WHERE FIELD1 IN (SELECT FIELD2 FROM TABLE2)). Both do not have primary keys. And is EXTERNAL TABLE. How do I proceed?

I managed to solve with Phalcon\Mvc\Model\Resultset\Simple it worked perfectly.