Laravel:一个是对多个关系,获取外键值


Laravel : One is to Many Relationship, get foreign key value

我目前正在研究产品类别和产品关系这就是一个比很多。我想知道为什么我有这个错误

调用未定义方法stdClass::products()

这是我的产品模型

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product extends Model
{
  public $table = "products";
  public $fillable = ['productcategory_id',
                    'name',
                    'description',
                    'price',
                    'pic',
                    'availability',
                    'featured',
          ];
  public function productcategory()
  {
      return $this->belongsTo('App'ProductCategory');
  }
}

这是我的产品类别模型

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class ProductCategory extends Model
{
  public $table = "productcategories";
  public $fillable = ['name',
                    'description',];
  public function products(){
      return $this->hasMany('App'Product','productcategory_id','id');
  }
}

和Here's my view file

@foreach($productcategories as $productcategory)
   @foreach($productcategory->products() as $product)
     {{ $product->name }}
    @endforeach
 @endforeach

请帮助我,我总是得到这个错误。

只是在黑暗中拍摄,但我将首先从$productcategory->products()中删除视图文件中的括号。如果这不能解决问题,在控制器中添加($productcategories)并验证您正在传递ProductCategory的集合,因为我不希望产生的错误包括对"stdClass"的引用。