Is there (UPSERT) or (MERGE) in Phalcon?
Compatibily for:
- Mysql
- Postgresql
- Sqlite
|
Sep '16 |
8 |
2608 |
0 |
$model->save($upsertArray);
See: https://docs.phalcon.io/en/latest/reference/models.html#creating-updating-records
CREATE TABLE public.config
(
collection character varying(255) NOT NULL DEFAULT ''::character varying, -- Primary Key: Config object collection.
name character varying(255) NOT NULL DEFAULT ''::character varying, -- Primary Key: Config object name.
data bytea, -- A serialized configuration object data.
CONSTRAINT config____pkey PRIMARY KEY (collection, name)
)
I wish to insert or update the fields that were updated, also if you can not replace everything, only they changed.
Not with model, one query.
I created a function:
/**
* Helper method so we can re-try a write.
*
* @param string $name
* The config name.
* @param string $data
* The config data, already dumped to a string.
* @return bool
* @throws \Exception
*/
protected function doWrite($name, $data)
{
$type = $this->connection->getType();
switch ($type) {
case 'mysql':
$sql = 'INSERT INTO config ( collection, name, data ) '
. ' VALUES (:collection, :name, :data) '
. ' ON DUPLICATE KEY UPDATE '
. ' data = VALUES(data);';
break;
case 'pgsql':
$sql = 'INSERT INTO config (collection, name, data) '
. 'VALUES (:collection, :name, :data) '
. 'ON CONFLICT (collection, name) '
. 'DO UPDATE SET data = EXCLUDED.data;';
break;
case 'sqlite':
$sql = 'INSERT OR REPLACE INTO config (collection, name, data) '
. 'VALUES (:collection, :name, :data);';
break;
default:
throw new \Exception('Only support Mysql, Postgres and SQLite');
break;
}
return (bool)$this->connection->execute(
$sql,
[
'collection' => $this->collection,
'name' => $name,
'data' => $this->encode($data)
],
[
Db\Column::BIND_PARAM_STR,
Db\Column::BIND_PARAM_STR,
Db\Column::BIND_PARAM_BLOB
]
);
}
Could you give me an example with the model, please.
I want to know the inner workings.
Oh okay. I would just use Model because it has already dynamic update built-in.
is antipattern???
// anti pattern to upsert
$fbUser = \App\Models\Profile::findFirst($fbId);
if (empty($fbUser)) {
$fbUser = new \App\Models\Profile();
$fbUser->id = $fbId;
}
// ~ anti pattern to upsert
$fbUser->status = 2;
Example drupal 8 merge query:
https://www.drupal8.ovh/en/tutoriels/46/database-merge-insert-or-update-if-exist
If you really wnat this then the best would be just implement it to phalcon, if you don't know zephir then you can just do it for incubator in plain php https://github.com/phalcon/incubator/tree/master/Library/Phalcon and someone will port it to phalcon. I was never using merge/upsert. Don't know how they work exactly and how it should work in active record pattern.