Laravel 从具有 belongstoMany 的 ID 获取模型

Laravel get model from ID with belongtoMany

我正在使用 Laravel 4 构建应用程序,但在 tables 中遇到了一些问题。

有 3 个 table 类别,产品,products_categories(透视)

类别模型

public function product()
{
    return $this->belongsToMany('Product', 'products_categories');

}

产品型号

public function category()
{
    return $this->belongsToMany('Category', 'products_categories');
}

products_categories table 有 product_idcategory_id 列。

我想要的是获取该类别中的所有产品并在浏览量中列出它们

$category = Category::where('id' , '=' , '7')->first();

    foreach($category->product as $product){

        echo $product->id;
    }

我可以看到与特定类别相关的产品 ID,但是当我想使用它来获取所有产品本身时,例如:

    $category = Category::where('id' , '=' , '7')->first();

    foreach($category->product as $product){

        $product = Product::where('id' , '=' , $product->id )->get();
    }

    return View::make('index')->with('product',$product);

它不起作用 :( 出现此错误

Trying to get property of non-object

我试过了

$category = Category::where('id' , '=' , '7')->first();

    $product = array();

    foreach($category->product as $product){

        $product[] = Product::where('id' , '=' , $product->id )->get();

    }

    return View::make('index')->with('product',$product);

这次它抛出这个错误

Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()

我该如何解决这个问题?

眼前的问题是您正在尝试重用 foreach 循环中的迭代器变量。这会导致您意想不到的结果。

foreach($category->product as $product) {
                              ^^^^^^^^
    $product = Product::where('id' , '=' , $product->id )->get();
    ^^^^^^^^
}

但是,没有必要这样做。 $category->product 已经是 Eloquent 个产品模型的集合。无需再次尝试检索单个产品;你已经有了它们。

如果您尝试将此集合传递给视图,您可以这样做:

return View::make('index')->with('product', $category->product);

此外,作为旁注,如果您试图通过 ID 查找记录,您可以使用 find() 方法:

$category = Category::find(7);