@asadbek2000 what's the problem to define relationship between tables?
Jul 28, 2021
5
Level 2
Join in Laravel and Relationship : I hava buy_material table and buying_material_item table , buy_material table include agent_id and date , buying_material_item table include material_id, material_price and quantity .
In my BuyMaterialController store function I want to create buymaterial
In there I want to insert value like this
{ "counter_agency_id":1, "date":"2021-07-28", "items":[ {"material_id":1,"material_price":1000,"quantity":5} ] }
but in my buy_material table and buying_material_item table has no relation , but i wanto insert in one request
public function store(BuyMaterialRequest $request) {
$buyMaterial = BuyMaterial::create($request->all());
$buyingMaterialItems = DB::table('materials')
->join('buying_material_item', 'materials.id', '=', 'buying_material_item.material_id')
->select('materials.*', 'buying_material_item.quantity')
->get();
$buyMaterial = attach($buyingMaterialItems);
return response()->json(['created'=>'Successfully Created']);
}
Level 2
public function store(BuyMaterialRequest $request) { $buyMaterial = BuyMaterial::create($request->all());
$buyMaterialItems = collect($request->items)->map(fn($buyMaterialItem) => [
"material_id" => $buyMaterialItem['material_id'],
"price"=>$buyMaterialItem['price'],
"quantity" => $buyMaterialItem['quantity'],
"total"=>$buyMaterialItem['price']*$buyMaterialItem['quantity']
]);
$totalPrice = $buyMaterialItems->sum('total');
$buyMaterial->materials()->attach($buyMaterialItems);
return response()->json(['created'=>'Successfully Created','totalPrice'=>$totalPrice]);
}
Please or to participate in this conversation.