簡體   English   中英

多對多Laravel關系

[英]ManyToMany Laravel Relationship

我有我的模特產品:

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;
}

但這不起作用,我想知道...我如何列出?

我已經嘗試了所有..並且它說Property [title]在此集合實例上不存在。

謝謝

您看到的錯誤很可能是由於輸入錯誤。 它應該是:

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

除此之外,您的其余代碼看起來也不錯。 修正拼寫錯誤后,您可以通過以下方式訪問每個產品的類別:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM