我需要将示例中的数据(price
)发送到 View ,但在foreach
内部。
在我的项目中,我在数据库的一张表中包含产品数据(title
、img
等)。
但是每种产品都有很多变体,我将这些变体放在另一个表中。
在 View
中,我有foreach
,它循环我的12
产品。
我需要将价格
放入每个产品
中。
问题是在我的 Controller 中定义每个产品的 id
。
products.blade.php:
@foreach($products as $product)
<div> {{ here I need to put the price }} </div>
<div> {{ $product->slug }} </div>
@endforeach
ProductsController.php:
// all prices for my variants
$variants_prices = Variants
::where('product_slug', '=', $slug)
->get('attribute_price');
// minimum price
$min_price = $variants_prices
->where('attribute_price', $variants_prices->min('attribute_price'))
->first();
// take value of minimum price from all variants
$pdt_min_price = $min_price->attribute_price;
return view('products.index')
->with('pdt_min_price', $pdt_min_price);
我的 blade
文件中需要有这样的东西:
如果有人能帮助我解决这个问题,我将非常高兴。
最佳答案
您可以在模型中定义产品和变体之间的关系
在您的产品
模型中:
function variant()
{
return $this->hasMany('App\Variant', 'foreign_key');
}
然后你可以使用以下方法获取变体:
$products = Product::with(['variant'])->get();
然后在循环中您可以使用其 key 访问变体:
{{ $product->variant[$key]['price'] }}
关于php - Laravel 在 foreach 中将数据从一个模型发送到另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56081345/