控制器中的多对多关系

时间:2018-11-21 20:10:01

标签: php laravel many-to-many

我希望我的控制器向我的视图发送产品列表,以下是我目前的尝试方法:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
} 

Wishlist.php

public function products()
{
    return $this->hasMany('App\Models\Product');
}

WishListsController.php

public function index()
{
    $wishList = WishList::find(1);
    $products = $wishList->products()->get();
    return view('WishLists.index',compact('products'));
}

错误:

SQLSTATE[42S22]: Column not found: 1054 Champ 'products.wish_list_id' unknow in where clause (SQL: select * from `products` where `products`.`wish_list_id` = 1 and `products`.`wish_list_id` is not null)

它似乎在表产品中查找id,而不是在多对多表中查找?但是我找不到原因。

1 个答案:

答案 0 :(得分:0)

ProductWishList组成Many to Many relationship(至少对我来说)。在m---m关系中,belongsToMany()方法需要在两端定义。

如果这个假设是正确的(关系设计),请按照以下方式定义您的关系:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\WishList', 'custom_table_name');
    */ 
}

WishList.php

public function products()
{
    return $this->belongsToMany('App\Models\Product');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\Product', 'custom_table_name');
    */ 
}

现在,在您的控制器中:

WishListController.php

public function index()
{
    $products = WishList::find(1)->products()->get();

    return view('WishLists.index', compact('products'));
}