首页 > 解决方案 > 如何通过 $product->name 等于 laravel 中的 $order->product 的另一个表获取价格?

问题描述

我有 2 张桌子:产品和订单。按顺序,我想通过产品表获取价格。

形式

<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">
        <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>

下面是我的订单控制器。我不明白如何获取价格,因为我们从表单中获取的值位于数组中,我想将其转换为字符串,通过该名称,我希望通过 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');
}

订单表 在此处输入图像描述

产品表 在此处输入图像描述

订购型号

use HasFactory;

protected $table = 'orders';

protected $fillable = [
    'order_by',
    'product',
    'quantity',
];

产品型号

use HasFactory;

protected $table = 'products';

protected $fillable = [
    'name',
    'brand',
    'price',
    'detail',
    'image',
];

标签: phplaravellaravel-8

解决方案


您应该将 product_id 作为外键存储在订单表中,并在订单和产品之间建立关系。而且您不必在订单表中存储产品价格和名称。

订单模式

use HasFactory;

protected $table = 'orders';

protected $fillable = [
    'order_by',
    'product',
    'quantity',
];

public function product()  
{
  return $this->belongsTo('App\Product', 'product_id'); 
}

你必须得到这样的产品名称和价格

{{$order->product->name}}
{{$order->product->price}}

推荐阅读