在Eloquent Query中的if / else逻辑

时间:2013-07-02 11:57:31

标签: 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', '=', '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(),具体取决于路由是指向子类别还是实际页面。

根据此条件更改变量名称以及使用其他刀片模板的返回值也很不错。

这种方法可行吗?感谢。

更新:我几乎让它使用:

http://paste.laravel.com/zod

问题是,如果$ sub_category的查询没有返回任何内容,我会发现模型未找到错误。

1 个答案:

答案 0 :(得分:0)

好的,我使用了它:

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);
    }
});

可能有一种更好的方式,所以如果有人能够对它有所了解那就太棒了。