2017-06-21 17 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; 
} 

しかし、それは動作しません、私は知りたいです...私はどのようにリストすることができますか?

私はすべてを試しましたが、Property [title]はこのコレクションインスタンスに存在しません。あなたが見ている

おかげ

+0

'dd($ product)'は何ですか? – apokryfos

答えて

2

誤差はタイプミスによる可能性が高いです。それは次のようにする必要があります。

その他のコードは正常です。タイプミスを修正すると、各製品のカテゴリにアクセスできるようになります。

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

返事をありがとう、それは働いた:D、私はそのカテゴリにいくつの製品が含まれているかをカウントしたいのだろうか?どうやってやるの?感謝。 –

+0

私はおそらくその逆の方法にアプローチするでしょう - すべてのカテゴリをクエリし、それぞれのプロジェクトの数を数えます。 – jackel414

+0

完璧でした! :D –