)我有方法:
public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
$query->where(['category_id', 19]);
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
此方法返回所选类别中的产品列表。编号19是选择的ID类别。所选类别中的产品列表的URL如下所示:www。[...] magazyn_michal / public / addcategory / 19 问题是:如何传递动态值数字方法的URL的ID类别(19)?? 我试试这个(但不能正常工作):
public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
$query->where(['category_id' => $categories->id]);
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
Laravel回来了:
未定义的变量:类别
这种方式也不起作用:
public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
$query->where('category_id', Input::get('category_id'));
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
Laravel什么都不回来。所选类别中的空产品列表。
routes.php文件:
Route::get('/', 'ProductsController@index');
Route::get('/contact', 'PagesController@contact');
Route::resource('/addarticle', 'ArticlesController');
Route::resource('/addcategory', 'CategoriesController');
Route::resource('/listcategory', 'CategoriesController@listCategory');
Route::resource('/warehouse', 'ProductsController');
Route::auth();
Route::get('/home', 'HomeController@index');
model category.php:
public function products(){
return $this->hasMany('App\Product');
}
model product.php:
public function category(){
return $this->belongsTo('App\Category');
}
我使用这个:https://laravel.com/docs/5.2/eloquent-relationships#constraining-eager-loads
答案 0 :(得分:1)
在这种情况下,您应该使用路由模型绑定。您可以让路由/categories/19
返回Category
对象,而不仅仅是ID。这可能已经发生,当您致电findOrFail
时会导致错误。
退房:https://laravel.com/docs/master/routing#route-model-binding
您还应该使用Laravel关系,因此您可以将此功能放在Category
课程中:
public function products(){
return $this->belongsToMany('App\Product');
}
更多阅读关系:https://laravel.com/docs/master/eloquent-relationships
如果同时执行这两项操作,您的控制器方法将如下所示:
public function show(Category $category){
$products = $category->products;
return view('categories.showcategory', compact('category', 'products'));
}
答案 1 :(得分:1)
我想我已根据您向我展示的所有测试而得到它。 $ categories超出了您的查询范围。试试这个:
public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) use ($categories) {
$query->where('category_id', $categories->id)
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
use声明将类别放在匿名函数的范围内
答案 2 :(得分:0)
好的我修复了这个问题。现在它正在运作;)
public function show($id){
$categories = Category::findOrFail($id);
$categoryID = Input::get('category_id');
$productsList = Category::with(['products' => function ($query) use($id) {
$query->where('category_id', '=' ,$id);
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}