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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With