Php 此集合实例上不存在属性[products]

Php 此集合实例上不存在属性[products],php,laravel,Php,Laravel,在我的应用程序中,我首先使用products检索产品类别,现在我想从产品类别中提取产品,但出现以下错误: Property [products] does not exist on this collection instance. 这就是我如何首先获得类别,然后获得产品 $productCategories = ProductCategory::with('products')->get(); //This works $products = $productCategories-

在我的应用程序中,我首先使用products检索产品类别,现在我想从产品类别中提取产品,但出现以下错误:

Property [products] does not exist on this collection instance.

这就是我如何首先获得类别,然后获得产品

$productCategories = ProductCategory::with('products')->get(); //This works

$products = $productCategories->products; //Then this gives me error
以下是我的模型和迁移:

class Product extends FilterableModel
{


    protected $table = 'products';

    public function category()
    {
        return $this->belongsTo('App\Models\ProductCategory', 'productcategory_id');
    }

因此,您的
$productCategories
变量是
productCategories
实例的集合。 如果您想获得所有这些产品的产品,您需要在其中循环:

foreach ($productCategories as $productCategory) {
   dump($productCategory->products);
}
如果您想获得
productCategory
之一的产品,您需要从数据库中选择它:

$productCategory = ProductCategory::findOrFail($productCategoryId);
dump($productCategory->products);

希望有帮助。

因此,您的
$productCategories
变量是
ProductCategory
实例的集合。 如果您想获得所有这些产品的产品,您需要在其中循环:

foreach ($productCategories as $productCategory) {
   dump($productCategory->products);
}
如果您想获得
productCategory
之一的产品,您需要从数据库中选择它:

$productCategory = ProductCategory::findOrFail($productCategoryId);
dump($productCategory->products);
希望能有帮助

$productCategory = ProductCategory::findOrFail($productCategoryId);
dump($productCategory->products);