php - 如何通过 $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',
];
解决方案
您应该将 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}}
推荐阅读
- flutter - 如何使用 BottonNavigationBar pushAndRemoveUntil 子屏幕?
- javascript - (MongoDB / Mongoose)增加对象数组中的值
- python - Python:kivy安装错误,不是git仓库
- php - SQL 搜索是否包含关键字随机
- elasticsearch - 邮递员预请求脚本不排除字段
- javascript - 为什么 passport.authenticate 没有调用?
- python - 使用 import keras 和 import tensorflow.keras 的区别?
- flutter - Flutter setState 不更新子元素
- java - 在 Android Studio 中将嵌套的 JSON 反序列化为 Java
- linux - 使用 MAP_FIXED 时 mmap addr 是否需要页面对齐