首页 > 解决方案 > 此集合实例上不存在属性 [产品]

问题描述

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

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');
    }
class ProductCategory extends FilterableModel
{


    protected $table = 'productcategories';


    public function products()
    {
        return $this->HasMany('App\Models\Product', 'productcategory_id');
    }


}
Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title');
            $table->string('slug');
            $table->string('url');
            $table->text('body')->nullable();
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(false);
            $table->boolean('isFeatured')->default(false);
            $table->integer('stock')->default(0);
            $table->decimal('originalPrice', 5,2)->default(0.00);
            $table->decimal('finalPrice', 5,2)->default(0.00);
            $table->timestamps();
        });
Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('slug')->unique();
            $table->string('url')->unique();
            $table->text('body')->nullable();
            $table->string('image')->default(config('app.defaultImage'));
            $table->string('icon')->default('fa fa-tag');
            $table->boolean('isVisible')->default(false);
            $table->boolean('isFeatured')->default(false);
            $table->timestamps();
        });

标签: phplaravel

解决方案


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

foreach ($productCategories as $productCategory) {
   dump($productCategory->products);
}

如果您想获得其中一个产品,则productCategory需要从数据库中选择它:

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

希望能帮助到你。


推荐阅读