If I got it right why don't you just increment the counter on each transaction success ?
How to perform a update operation in loop if there is no other option in laravel or any platform ?
This question is in my mind from so long time and I was trying to figure it out what would be the best approach for this scenario . I have done multiple projects in my little career and so many times i've came to a point where I have to forcibily try my queries in loops as I dont see any other option which is more fruitful .
Now there is one scenario in my current project in which I have multiple payment transactions are done regularly and they are from different banks
Now there is one cron which runs at every night which takes all the data from transactions and after that set counts of transactions respective of particulars banks and update it to those banks tables .
For better understanding let me elaborate this condition
Transaction 1 Bank 1
Transaction 2 Bank 2
Transaction 3 Bank 1
Transaction 4 Bank 2
Transaction 5 Bank 2
Transaction 6 Bank 1
Transaction 7 Bank 3
Transaction 8 Bank 4
Transaction 9 Bank 5
Transaction 10 Bank 3
now what cron does is collect all the transactions and banks grouping is done so that we have counts of all banks with number of transactions done Now we update those records in bank table
Bank 1 3
Bank 2 3
Bank 3 2
Bank 4 1
Bank 5 1
so this process runs everyday so that I have record of all banks with number of transactions processed now there is no problem so far in my work but actually there is one case which I am in doubt to achieve this work I have this query for my cron
if ($aepsRecords->count()) {
DB::transaction(function () use ($aepsRecords) {
foreach ($aepsRecords as $record) {
DB::connection('ipay_app_bc__write')
->table('bank_summary')
->where('bank_iin', $record->bankiin)
->update(['aeps_preference' => $record->count]);
}
});
}
see I have recorded all the records in loop which I really dont believe that this is good approach so I just wanted to know if there is some scenario in daily cases what would be the best way to do this kind of query updates or retrieval
I hope everything is clear if not please share your views
Thank you !!
@rohansinghrawat If your table bank_summary has the column bank_iin as primary or unique index, you can use upserts https://laravel.com/docs/9.x/queries#upserts and do that in one query.
You cannot avoid the loop but you can (and should) avoid the multiple queries
if ($aepsRecords->count()) {
$records = [];
foreach ($aepsRecords as $record) {
$records[] = [
'bank_iin' => $record->bankiin,
'aeps_preference' => $record->count
];
}
DB::transaction(function () use ($records) {
DB::connection('ipay_app_bc__write')
->table('flights')
->upsert($records);
});
}
Please or to participate in this conversation.