Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment value in database using Propel

Tags:

php

mysql

propel

I'm new to propel, and I'm looking for a way to increment a value in my MySQL database, without having to do a full read-update-write cycle. Such as this:

UPDATE books SET popularity = popularity + 1 WHERE id = 123

Of course I can do:

$book = new BookQuery::create()->findPk(123);
$book->setPopularity($book->getPopularity() + 1);
$book->save();

But that would result in 2 queries (the SELECT and the UPDATE).

Is there a neat way to do this in Propel?

like image 675
Léon Melis Avatar asked Sep 23 '15 16:09

Léon Melis


1 Answers

Is there a neat way to do this in Propel?

No, but there is a way. ;) You can use the Criteria::CUSTOM_EQUAL parameter with Criteria->add():

$con = Propel::getConnection( BooksPeer::DATABASE_NAME, Propel::CONNECTION_WRITE );
$whereCriteria = BooksQuery::create()->filterById( 123 );
$valuesCriteria = new Criteria( BooksPeer::DATABASE_NAME );
$valuesCriteria->add( BooksPeer::POPULARITY, BooksPeer::POPULARITY . " + 1", Criteria::CUSTOM_EQUAL );
BasePeer::doUpdate( $whereCriteria, $valuesCriteria, $con );

This is how the sortable behavior implements rank shifting.

like image 67
Matthew Leffler Avatar answered Oct 23 '22 06:10

Matthew Leffler