If statement 雄辩查询中的if/else逻辑
我需要能够根据路线封闭内的特定条件查询模型 我有这条路线:If statement 雄辩查询中的if/else逻辑,if-statement,model,laravel,laravel-4,eloquent,If Statement,Model,Laravel,Laravel 4,Eloquent,我需要能够根据路线封闭内的特定条件查询模型 我有这条路线: Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) { $category = Category::where('slug', $category_slug)->first(); $course = Course::leftJoin('categories', 'categories.id', '=', 'cou
Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) {
$category = Category::where('slug', $category_slug)->first();
$course = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
->where('categories.slug', '=', $category_slug)
->where('courses.slug', '=', $slug)
->orWhere('categories.parent_id', '=', $category->id)
->where('categories.slug', '=', $slug)
->firstOrFail();
return View::make('courses.show')->with('course', $course);
});
这部分工作正常,但我需要能够使用get()或firstOrFail(),这取决于路由指向的是子类别还是实际页面
基于此条件更改变量的名称以及使用不同刀片模板的返回值也很好
这种方法可行吗?谢谢
更新:我几乎可以使用:
Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) {
$category = Category::where('slug', $category_slug)->first();
$sub_category = Category::where('slug', $slug)->first();
if (!is_null($sub_category)) {
if ($sub_category->slug === $slug) {
$courses = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
->where('categories.parent_id', '=', $category->id)
->where('categories.slug', '=', $slug)
->get();
return View::make('courses.index')->with('courses', $courses);
}
} else {
$course = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
->where('categories.slug', '=', $category_slug)
->where('courses.slug', '=', $slug)
->firstOrfail();
return View::make('courses.show')->with('course', $course);
}
});
问题是,如果$sub_类别的查询没有返回任何内容,我将得到一个model not found错误。好的,我使用以下方法使其工作:
Route::get('courses/{category_slug}/{slug}', function($category_slug, $slug) {
$category = Category::where('slug', $category_slug)->first();
$sub_category = Category::where('slug', $slug)->first();
if (!is_null($sub_category)) {
if ($sub_category->slug === $slug) {
$courses = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
->where('categories.parent_id', '=', $category->id)
->where('categories.slug', '=', $slug)
->get();
return View::make('courses.index')->with('courses', $courses);
}
} else {
$course = Course::leftJoin('categories', 'categories.id', '=', 'courses.category_id')
->where('categories.slug', '=', $category_slug)
->where('courses.slug', '=', $slug)
->firstOrfail();
return View::make('courses.show')->with('course', $course);
}
});
可能有更好的方法,所以如果有人能解释一下,那就太好了。如果你不想抛出错误,就先使用
。然后检查$sub_category
是否为空,以确保得到结果。