首页 文章

Laravel通过belongstoMany从ID获取模型

提问于
浏览
3

我正在使用Laravel 4构建应用程序,但是对于数据透视表有一些问题 .

共有3个表格分类,产品,产品_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

我怎么解决这个问题?

1 回答

  • 4

    当前的问题是你试图从foreach循环中重用你的迭代器变量 . 这会导致您意想不到的结果 .

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

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

    如果您尝试将此Collection传递给视图,则可以执行以下操作:

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

    此外,作为附注,如果您尝试按ID查找记录,则可以使用 find() 方法:

    $category = Category::find(7);
    

相关问题