【问题标题】:Laravel Nesting to 4 levels not workingLaravel 嵌套到 4 个级别不起作用
【发布时间】:2016-12-05 06:16:59
【问题描述】:

我有如下关系:

类别 -> 子类别 -> 产品 -> 价格

一个类别包含 X 个子类别。 一个子类别包含 X 个产品。 一个产品包含 X 个价格(新价格、旧价格、每次价格变化一条记录)

我想做以下事情:

@foreach($categories as $category)
    [...]
    @foreach($category->subcategories as $subcategory)
        [...]
        @foreach($subcategory->products as $product)
            [...]
                @foreach($product->prices as $price)


[... @endforeach x4 ...]

前 3 个级别正在运行。但是,当使用第 4 个 ($product->prices) 时,我收到 Trying to get property of non-object 错误。

模型中的关系:

Category.php

class Category extends Model
{
    public function subcategories()
    {
        return $this->hasMany('App\SubCategory');
    }
}

SubCategory.php

class SubCategory extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

Product.php

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function subcategory()
    {
        return $this->belongsTo('App\SubCategory');
    }

    public function price()
    {
        return $this->hasMany('App\ProductPrice');
    }
}

ProductPrice.php

class ProductPrice extends Model
{
    public function product()
    {
        return $this->belongsTo('App\Product');
    }
}

这是我发送到我的视图的内容:

class PageController extends Controller
{
    public function showMainPage()
    {
        $categories = Category::with('subcategories')->get();

        $data = array(
          "categories" => $categories,
        );

        return view('index')->with($data);
    }
}

这工作正常,即使是产品,但在使用 ProductPrices 时开始出现错误。

【问题讨论】:

  • $categories = Category::with('subcategories.products.prices')->get();
  • 完全相同的错误@GONG
  • 您尝试拨打$product->prices,而您的关系是price

标签: laravel eloquent relational-database


【解决方案1】:

正如@GONG 所说,更改您的代码以使用急切加载,这将比使用一些 foreaches 运行得快得多。

查看 laravel 文档:https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

【讨论】:

  • 我急于加载,还是我错了?但我需要对它们进行分析,因为我想从数据库中加载所有记录并显示它们。例如,我实际上使用 $category->subcategories->products 来加载子类别中的所有产品。如果我做错了什么,你能解释一下吗?
猜你喜欢
  • 1970-01-01
  • 2022-07-14
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
相关资源
最近更新 更多