[英]Many to many relationships in the controller
我希望我的控制器向我的视图发送产品列表,这是我目前的尝试方式:
产品.php
public function wishLists()
{
return $this->belongsToMany('App\Models\WishList');
}
愿望清单.php
public function products()
{
return $this->hasMany('App\Models\Product');
}
愿望清单控制器.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 而不是在多对多表中查找? 但我找不到原因。
Product
和WishList
建立了多对多的关系(至少对我而言)。 在m---m
关系中,需要在两端定义belongsToMany()
方法。
如果此假设成立(关系设计),请定义如下关系:
产品.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');
*/
}
愿望清单.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');
*/
}
所以现在,在你的控制器中:
愿望清单控制器.php
public function index()
{
$products = WishList::find(1)->products()->get();
return view('WishLists.index', compact('products'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.