私は、プロセスの最後の計算と多くの関係に多くで更新何かについて問題を抱えています。テーブルの例
stock_transports
stock_tranportation_details
stock_entries
stock_entry_details
私はシステムに完全のボタンをクリックした場合、私は条件同じのitem_idとref_codeと数量の合計でstock_transpotation_detailsを更新したいです
その結果、私はこのように願っています
このような私の進行コード
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
];
}
}
そして間違った結果、stock_entry_detailsの自分だけの計算の1つを得たpleseは助けその後、ダンプそのI更新stock_transport_detail後またはちょうど私は、MySQLのトリガまたはより良いロジックを持つコードまたは例えば別の方法のための解決策を見つけます
私はそれらの美しさは、彼らが唯一のデータベース整数で作業する必要はありませんで、ここではLaravelの関係を利用することになります。あなたの株式の詳細クラスでは、輸送の詳細に関係を追加します。あなたのクラスを仮定すると命名さStockEntryDetail
とStockTranportationDetail
。
class StockEntryDetail {
public function transportDetails() {
return $this->hasMany(StockTranportationDetail::class, 'ref_code', 'ref_code');
}
}
立派なパフォーマンスを持っているために、私は、インデックスうref_code
と、両方のテーブルの上に「ITEM_ID」。
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']);
});
そして、あなたは、次のようにコードを最適化することができます。TransportDetailsを持っているとのitem_idが同じであるすべてのStockDetailsを見つけ、これは迅速なパフォーマンスのためのクエリを使用して行われます。データを更新し、設定は完了です。
// 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();
}
あなたのスコープと質問が大きくて少し混乱で、私は理解し考え、利用してLaravel
機能を、私は解決策がクリーンで、より管理されるべきだと思います。一般的には中Laravel
、あなたは常にデータベースにEMを保存することができますようなモデルを維持し、あなたが何かを間違ってやっている配列にモデルを変換するために開始したとき。