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.

On duplicate key update


I've been looking through the documentation (and Google) for how to set on duplicate key update in the models. All I've seen is basically writing custom queries to do this, but I feel that there must be some behavior that can be set in the model initialization or similar. In my table, I have a unique index (col1, col2), and basically, it only contains two values. If it does not exist, create it. If it exists, update col2.

Can someone point me in the right direction?


// dimhoLt


on duplicate key update is not a sql standard. It's pretty much specific to MySQL. If you want your scripts to actually execute the mysql query with on duplicate key update, with Phalcon, you will have no choice but to have custom queries. If you just want the logic of the "on duplicate key update" (i doubt it), you can use beforeValidationOnCreate, check with select if the primary and/or unique key exist and if found, run update and fail validation so the insert wont be done. If you are running slave/master mysql servers, make sure to check if the keys exist using the master connection, not on the slave connection.


Thank you for your answer. I'm not sure, however, why there would be any doubt that I would want this logic. Is there perhaps some best practices you're referring to that I may have missed?

i said "i doubt it" just because from your question i was 99% sure that you want to run a single mysql query INSERT ... ON DUPLICATE KEY instead of 2 queries.It was not because of some "best practices" thing :) From my unpopular point of view, MySql's LIMIT,and ON DUPLICATE KEY should become sql standard.


I see. Thank you for your extended explanation =) Yes, I was looking to do that. However, in this case, I'm going to solve this particular issue in a Service using this particular model instead to retain a consistent model behaviour / interface.

I agree, those things are wonderful and should exist everywhere. Recently switched to MariaDB which I so far like very well (MySQL fork ofc).

Thank you again!