php - Laravel 在 foreach 中将数据从一个模型发送到另一个模型

标签 php mysql laravel eloquent laravel-query-builder

我需要将示例中的数据(price)发送到 View ,但在foreach内部。 在我的项目中,我在数据库的一张表中包含产品数据(titleimg 等)。

但是每种产品都有很多变体,我将这些变体放在另一个表中。 在 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 文件中需要有这样的东西:

enter image description here

如果有人能帮助我解决这个问题,我将非常高兴。

最佳答案

您可以在模型中定义产品和变体之间的关系

在您的产品模型中:

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/

相关文章:

php - 根据 Laravel 中的上一页重定向到不同的页面

php - 将动态数据传递给javascript

php 从巨大的文本文件中提取一行

MySQL Workbench session 看不到数据库的更新

php - 在 php 的表中没有删除值?

php - 获取附近位置的最佳方式?

php - 我的选择语句正确吗

php - Laravel wherebetween 不接受负数

php - 通过 laravel 中的 timthumb php 脚本定义一个路由来显示图像

php - 如何修复它在 laravel 5.3 中调用字符串的成员函数 diffForHumans()