php - 此集合实例上不存在属性 [产品]
问题描述
在我的应用程序中,我首先使用产品检索产品类别,现在我想从产品类别中提取产品,但出现以下错误:
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();
});
解决方案
因此,您的$productCategories
变量是ProductCategory
实例的集合。如果你想得到所有这些的产品,你需要循环它:
foreach ($productCategories as $productCategory) {
dump($productCategory->products);
}
如果您想获得其中一个产品,则productCategory
需要从数据库中选择它:
$productCategory = ProductCategory::findOrFail($productCategoryId);
dump($productCategory->products);
希望能帮助到你。
推荐阅读
- jquery - Github 将多个文件合并为单个压缩主文件
- javascript - 如何在垂直标签内容框的div内显示d3js图表?
- c++ - 检查模板参数是否“可调用”的 C++11 方法
- ignite - 点燃丢失的桌子
- java - 什么时候实现WebMvcConfigurer来配置Spring MVC?
- asp.net - 在 ASP.NET Webapp 中启用 Windows 身份验证
- python - 比较 2 个列表的元素并仅打印不同的元素
- xamarin - 带有自定义导航的 WebView 没有出现在 Xamarin 表单中
- python - 如何将环境变量从 .env 文件传递给 supervisord
- regex - 如何使用 sed 命令删除短语后的数字和日期时间?