2017-06-21 97 views
1

我有我的模型产品:多对多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() 
    { 
    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_categories

我想列出belog的产品所以我这样做:

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

foreach ($products as $product) { 
    $products->title; 
} 

但它不工作,我想知道...我如何列出?

我试过所有..它说在这个集合实例中不存在属性[标题]。

谢谢

+0

执行'dd($ product)',那里有什么? – apokryfos

回答

2

您看到的错误可能是由于输入错误。它应该是:

foreach ($products as $product) { 
    $product->title; 
} 

除此之外,其余代码看起来不错。修复错字应允许您通过以下方式访问每个产品的类别:

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

感谢您的回复,它的工作原理是:D,我想知道是否要计算该类别中有多少产品?我怎样才能做到这一点?谢谢。 –

+0

我可能会采用相反的方式 - 查询所有类别,然后计算每个类别中的项目数量。 – jackel414

+0

完美的工作! :d –