【问题标题】:if/else Logic in Eloquent QueryEloquent Query 中的 if/else 逻辑
【发布时间】:2013-06-29 18:52:39
【问题描述】:

我需要能够根据路线闭合中的特定条件查询模型。

我有这条路线:

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 的查询没有返回任何内容,我会收到模型未找到错误。

【问题讨论】:

  • 如果您不想抛出错误,请使用first。然后检查$sub_category 是否为空,以确保得到结果。

标签: if-statement model laravel laravel-4 eloquent


【解决方案1】:

好的,我可以使用:

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

可能有更好的方法,所以如果有人能对此有所了解,那就太好了。

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多