I have problem about update something in many to many relationship with calculate of the end of process. For table example
stock_transports
stock_tranportation_details
stock_entries
stock_entry_details
if i click button of complete in system, i want to update stock_transpotation_details with sum of qty with condition same item_id and ref_code
and the result i hope like this
my progress code like this
foreach($stockEntry->stock_transport->details()->get() as $detail) {
$arr[$detail->item_id.'_'.$detail->ref_code] = $detail->id;
}
$total_qty = 0;
foreach($stockEntry->details as $detail) {
if($arr[$detail->item_id.'_'.$detail->ref_code]) {
$total_qty += $detail->qty;
$arr[$detail->item_id.'_'.$detail->ref_code] = [
'qty' => $total_qty,
'ref_code' => $detail->ref_code,
'item_id' => $detail->item_id
];
}
}
and after that i update stock_transport_detail or just dump then got the wrong result, their just calculate one of the stock_entry_details plese help me find the solution for the code or another way for example with mysql trigger or better logic
I would utilise Laravel relationships here, the beauty of those, is they don't have to work with database integers only. In your stock details class, add a relationship to the transport details. Assuming your classes is named StockEntryDetail
and StockTranportationDetail
.
class StockEntryDetail {
public function transportDetails() {
return $this->hasMany(StockTranportationDetail::class, 'ref_code', 'ref_code');
}
}
To have respectable performance, i would index ref_code
and 'item_id' on both tables.
Schema::create('stock_entry_details', function (Blueprint $table) {
$table->index(['ref_code', 'item_id']);
});
Schema::create('stock_tranportation_details', function (Blueprint $table) {
$table->index(['ref_code', 'item_id']);
});
Then you can optimize your code to the following. Find all StockDetails that has TransportDetails and the item_id is the same, this is done with a query for quick performance. Update the data and you are done.
// Eager load the relationships we are going over
$stockEntry = StockEntry::with('details.transportDetails')->find($id);
foreach ($stockEntry->details as $detail) {
// find all with the same item_id, ref_code is done by relationship.
$transportDetailsCount = $detail->transportDetails()->where('item_id')->count()
// update your data
$detail->qty = $transportDetailsCount;
$detail->save();
}
Your scope and question is big and a little confusing, i think i understand and by utilizing Laravel
features, i think the solution is cleaner and should be more manageable. In general in Laravel
when you start to convert your models into arrays you are doing something wrong, keep the models as you can always save em to the database.