我有复杂的查询和关系,我不太了解。我是Laravel的新人。无论如何,我正在寻找一种用slugs而不是ID来加载它的方法。
这是控制器中的功能
public function index( $category_id)
{
$Category = new Category;
$allCategories = $Category->getCategories();
$category = Category::find($category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', $category_id)->where('parent_id','!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
$items = Item::whereIn('category_id',$array)->where('published', 1)->paginate(5);
} else {
$items = Item::where('category_id' ,$category_id)->where('published', 1)->paginate(5);
}
return view('list', compact('allCategories','items'));
}
这些是模型中的关系
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->paginate(40);
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id )
{
return Item::where('category_id', $category_id)->count();
}
这就是我的路线
Route::get('list/{category}', 'ListController@index')->name('list');
目前正在加载http://example.com/list/1之类的网址,其中1是ID。我想知道当前的设置是否可以像http://example.com/slug
那样我知道slu is是如何运作的。我只是无法理解如何在查询中使用它们而不是ID
答案 0 :(得分:0)
尝试将索引函数参数从$category_id
更改为$category_slug
删除此行$Category = new Category;
并更改此$category = Category::find($category_id);
对此:$category = Category::where('slug', $category_slug)->first();
*假设您在类别表中有唯一的slug
答案 1 :(得分:0)
在处理之前,您可以使用explicit Route Model Binding来获取您的类别。
在RouteServiceProvider
中,您需要绑定模型:
Route::bind('category', function ($value) {
//Change slug to your column name
return App\Category::where('slug', $value)->firstOrFail();
});
然后,您可以输入提示类别。
例如在索引方法中:
public function index(Category $category)
{
$Category = new Category;
$allCategories = $Category->getCategories();
//This line is obsolete now:
//$category = Category::find($category_id);
//...
}