Laravel用belongtoMany从ID中获取模型


Laravel get model from ID with belongtoMany

我正在使用Laravel 4构建一个应用程序,但数据透视表存在一些问题。

有3个表Categories,Products,Products_Categories(pivot)

类别模型

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

产品型号

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

products_categories表具有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);

它不起作用:(有这个错误

正在尝试获取非对象的属性

我试过这个

$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);

这次它抛出这个错误

Illuminate''Database''Eloquent''Model::setAttribute()缺少参数2

我该如何解决这个问题?

直接的问题是您试图重用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);