如何通过$PRODUCT-&>名称等于$ORDER-&>PRODUCT;的另一个表取价

2022-03-26 00:00:00 php laravel laravel-8
我有2个表PRODUCT和ORDER,我想通过PRODUCT表获取价格 这是我的表格

<div id="TextBoxDiv1">
     <input type="hidden" value="{{Auth::user()->name}}" name="order_by">
     <input class="text email" type="text" name="quantity[]" placeholder="Quantity" required="" id='textbox1' style="width: 230px; height: 41px; margin-top: 10px">
     <div class="form-group row">
     {{-- <label class="col-md-3 mt-3">Single Select</label> --}}
     <div class="col-md-9">
     <select class="select2 form-select shadow-none" style="width: 230px; height: 41px; margin-top: 10px" name="product[]">
             <option>Select Product</option>
             @foreach ($products as $product)
                   <option value="{{ $product->name }}">{{ $product->name }}</option>
              @endforeach
      </select>
    </div>
    </div>
 </div>

这是我的OrderController,我不知道如何获取价格,因为我们从表单中获得的值在数组中,我想将其转换为字符串,并通过该名称通过Products表获取价格

public function store(Request $request)
{
    $products = Product::all();
    $request->validate([
        'order_by' => 'required',
        'product' => 'required',
        'quantity' => 'required',
        'status' => 'sometimes',
        'price' => 'sometimes',
    ]);

    $order = new Order();
    $order->product = implode(',', $request->product);
    $order->quantity = implode(',', $request->quantity);
    // $order->price = ;
    $order->order_by = $request->order_by;
    $order->status = $request->status;
    $order->save();
    return redirect()->route('user/pending', compact('products'))->withSuccess('Done');
}
这是Orders表的图像

这是产品表的图片


解决方案

将选项的值设置为$PRODUCT-&>id,然后在控制器中获取价格

在刀片中:

@foreach ($products as $product)
   <option value="{{ $product->id }}">{{ $product->name }}</option>
@endforeach

在控制器中:

$product = Product::find(implode(',', $request->product));

$order->product = $product->name;
$order->price =$product->price;

相关文章