Php 多拉威尔关系

Php 多拉威尔关系,php,laravel,Php,Laravel,我有我的模型产品: class Product extends Model { protected $table = 'products'; protected $primaryKey = 'id_product'; protected $fillable = [ 'id_category', 'title', 'credit', 'created_at', 'updated_at', ]; public function categories() {

我有我的模型产品:

class Product extends Model
{
  protected $table = 'products';

  protected $primaryKey = 'id_product';

  protected $fillable = [
    'id_category', 'title', 'credit', 'created_at', 'updated_at',
  ];

  public function categories()
  {
    return $this->belongsToMany('App\Category', 'products_categories', 'id_product', 'id_category');
  }
}
我有我的分类模型:

class Category extends Model
{
   protected $table = 'categories';

   protected $primaryKey = 'id_category';

   protected $fillable = [
     'category', 'created_at', 'updated_at',
   ];

   public function products()
   {
       return $this->belongsToMany('App\Product', 'products_categories', 'id_product', 'id_category');
   }
}
我有我的桌上产品类别

我想列出属于某一类别的产品,所以我要这样做:

$products = Product::with('categories')->get();

foreach ($products as $product) {
  $products->title;
}
但它不起作用,我想知道。。。我如何列出

我都试过了。。它说这个集合实例上不存在属性[title]


谢谢

您看到的错误可能是由于打字错误。应该是:

foreach ($products as $product) {
  $product->title;
}
除此之外,其余代码看起来不错。纠正打字错误应允许您通过以下方式访问每种产品的类别:

foreach ($products as $product) {
    foreach ($product->categories as $category) {
        $category->name // or other attribute
    }
}

做一个
dd($product)
,里面有什么?谢谢你的回答,它起作用了:D,我想知道我是否想数一数那个类别中有多少产品?我该怎么做?谢谢。我可能会采取相反的方法——查询所有类别,然后计算每个类别中的项目数量。