Reputation: 87
I have this kind of weirdness with a update query in fat free frameworks
public function updateTransactionSalesFlush() {
$this->load(array('active=1 AND void=0'));
if (!$this->dry()) {
$data = array('salestemp' => 0);
$this->copyFrom($data);
$this->update();
}
}
This function update only the first record of selected but not all of them as expected. Am I doing something wrong or it's a bug??
The following query work fine using exec function:
UPDATE transactions SET salestemp=0 WHERE active= 1 AND void= 0
Upvotes: 1
Views: 226
Reputation: 3908
The load()
method loads all the records matching the specified criteria but maps only one record at a time.
You need then to use the next()
or skip()
methods to navigate through the set of records.
Your code updates only the first record because it lacks a loop. Here's how to fix it:
public function updateTransactionSalesFlush() {
$this->load(array('active=1 AND void=0'));
while (!$this->dry()) {
$this->salestemp=0;
$this->update();
$this->next();
}
}
Alternatively, you could call the find()
method instead of load()
:
public function updateTransactionSalesFlush() {
$records=$this->find(['active=1 AND void=0']);
foreach ($records as $record) {
$record->salestemp=0;
$record->update();
}
}
Of course, if you're updating a big number of records, you'd better execute a single UPDATE
statement via the exec()
method:
public function updateTransactionSalesFlush() {
$this->db->exec('UPDATE '.$this->table.' SET salestemp=0 WHERE active=1 AND void=0');
}
Upvotes: 1
Reputation: 180004
https://fatfreeframework.com/3.6/databases
By default, a data mapper's
load()
method retrieves only the first record that matches the specified criteria. If you have more than one that meets the same condition as the first record loaded, you can use theskip()
method for navigation:
Upvotes: 1