php - How to perform a conditional update using Fatfree framework's ORM
Get the solution ↓↓↓The situation consists of attempting to use F3 ORM (MySQL) with a state machine. A transaction/action should only be performed/persisted to the database if the original status allows for the transition to occur.
The code below loads the object, applies the new state, creates a new transaction, and attempts to ensure that the state in the database is as expected by updating the record to the new state.
$instance = $f3->get('domainObject')->load(['id=?', $id]);
$stateMachine = new StateMachine($instance, $config);
$originalState = $instance->stateA;
$stateMachine->apply($body['state']);
$db->begin();
$db->exec(
'UPDATE domainObject SET stateA=? WHERE stateA=?',
$instance->stateA,
$originalState
);
$instance->save();
$db->commit();
Even though the update and the save is within the same transaction the modification occurs even if the update fails to update the record (say when thestateA
has changed).
How can I use F3 ORM to conditionally update the model with a clause that statesstateA
should be a certain value?
Answer
Solution:
Assuming that$instance
is an instance ofDB\SQL\Mapper
and thatstateMachine->apply($body['state'])
modifies$instance->stateA
, then it should be as simple as:
$instance = $f3->get('domainObject')->load(['id=?', $id]);
$stateMachine = new StateMachine($instance, $config);
$instance->save();
Thesave()
method triggers anUPDATE
query, only if a field has been changed.
NB: be careful that theload()
method may returnFALSE
. Your code should handle that case.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.