【问题标题】:Laravel send data from one model to another inside a foreachLaravel 在 foreach 中将数据从一个模型发送到另一个模型
【发布时间】:2019-09-28 14:01:07
【问题描述】:

我需要将示例中的数据 (price) 发送到视图,但在 foreach 内部。 在我的项目中,我在数据库的一个表中拥有产品数据(titleimg 等)。

但是每个产品都有很多变体,我将变体放在另一个表中。 在view 中,我有foreach 循环我12 产品。

我需要将price 放入每个product 中。

问题是在我的控制器中定义每个产品的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 文件中包含这样的内容:

如果有人能帮我解决这个问题,我会很高兴。

【问题讨论】:

    标签: php mysql laravel eloquent laravel-query-builder


    【解决方案1】:

    您可以在模型中定义 Product 和 Variant 之间的关系

    在您的Product 模型中:

    function variant()
    {
      return $this->hasMany('App\Variant', 'foreign_key');
    }
    

    然后您可以使用以下方法获取变体:

    $products = Product::with(['variant'])->get();
    

    然后在循环中,您可以使用其密钥访问变体:

    {{ $product->variant[$key]['price'] }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      相关资源
      最近更新 更多