[英]Display the Name of Table using the ID of another table in Laravel Eloquent
Please, I have a function in my controller. 拜托,我的控制器中有一个功能。 I want to query the stock table to select the list of
product_id
and after select
, it should go to product table to display the NAME
of product to the user instead of product_id
. 我想查询库存表以选择
product_id
的列表, select
后,它应该转到产品表以向用户显示产品的NAME
,而不是product_id
。
public function getStockList()
{
$stock = DB::table("stocks")->pluck("product_id","product_id")->all();
$products = DB::table("products")->pluck("name")->where('id', $stock);
return view('shop.shop')->with(['stocks' => $stocks,
'stock' => $stock, 'products' => $products]);
}
My PHP blade has 我的PHP刀片有
{!! Form::select
(
'stock',
['' => 'Select'] +$stock,'',
array(
'class'=>'form-control',
'id'=>'country',
'style'=>'width:350px;'
)
)!!}
{!! Form::select
(
'product_id',
[''=>'Select Supplier'] + $products, null,
['class'=>'form-control']
)!!}
Basically, I don't want product_id
to be displayed to the user but the product name. 基本上,我不希望
product_id
显示给用户,而是显示产品名称。
Try this 尝试这个
public function getStockList()
{
$stock = DB::table("stocks")->pluck("product_id");
$products = DB::table("products")->whereIn('id', $stock)->pluck("name","id");
return view('shop.shop')->with([
'stocks' => $stocks,
'stock' => $stock,
'products' => $products
]);
}
Replace your product list select box with the following 用以下内容替换您的产品列表选择框
{!! Form::select('product_id',$products,null, ['class'=>'form-control','placeholder'=>'Select Products'])!!}
you need array to pass in form 你需要数组来传递表单
/* $product_array = ['1' => 'product 1', '2' => 'product 2', '3' => 'product 3']; */
so in your controller 所以在你的控制器中
$product_array = []
foreach($products as $product){
$product_array[$product->id] = $product->name;
}
return view('shop.shop')->with(['stocks' => $stocks,
'stock' => $stock, 'products' => $products , 'product_array'=>$product_array]);
And in your view 在您看来
{{!! Form::select('product_id', $product_array , null, ['class'=>'form-control'])!! }}
hope this will help. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.