laravel两条路线非常相似,呼叫另一条路线

时间:2014-10-12 08:35:39

标签: php laravel laravel-4

大家好,我有两条看起来相同的路线,除了一条有一个名为genre的额外参数,如何让它们调用它们的例程,而不是混淆它们。

Route::get('browse/{product_slug}', array(
    'as' => 'products.view_by_producttype', 
    function($slug)         
    {   
    }
))->where('product_slug', '[A-Za-z\-]+');

Route::get('browse/{producttype_slug}/{genre_slug}', array(
    'as' => 'products.view_by_producttype_genre', 
    function($productype_slug, $genre_slug) 
    {       
    }   
))->where('producttype_slug', '[A-Za-z\-]+')->where('genre_slug', '[A-Za-z\-]+');

升级代码和订单:

Route::get('browse/{producttype_slug}', array(
    'as' => 'products.view_by_producttype', 
    function($producttype_slug)         
    { 
        $producttype = ProductTypes::where('slug', '=', $producttype_slug)->firstOrFail();      

        $items = DB::table('products')->join('productvariations', function($join) {
            $join->on('productvariations.product_id', '=', 'products.id');
        })->where('producttype_id', '=', $producttype->id)->paginate(1);

        return View::make('products.view_by_producttype')->with(compact('items', 'producttype'));

    }
))->where('producttype_slug', '[A-Za-z\-]+');


Route::get('browse/{producttype_slug}/{genre_slug}', array(
    'as' => 'products.view_by_producttype_genre', 
    function($producttype_slug, $genre_slug) 
    { 
        $producttype = ProductTypes::where('slug', '=', $producttype_slug)->firstOrFail();

        $genre = GenreTypes::where('slug', '=', $genre_slug)->firstOrFail();

        $items = DB::table('products')->join('product_genretypes', function($join) {
            $join->on('product_genretypes.product_id', '=', 'products.id');             
        })->join('productvariations', function($join) {
            $join->on('productvariations.product_id', '=', 'products.id');
        })
        ->where('genretype_id', '=', $genre->id)
        ->where('producttype_id', '=', $producttype->id)
        ->paginate(1);

        return View::make('products.view_by_type_genre')->with(compact('items', 'producttype', 'genre'));

    }   
))->where('producttype_slug', '[A-Za-z\-]+')->where('genre_slug', '[A-Za-z\-]+');

1 个答案:

答案 0 :(得分:1)

只需交换订单 - 首先定义Genre路线 - 如下所示:

Route::get('browse/{producttype_slug}/{genre_slug}', array(
    'as' => 'products.view_by_producttype_genre', 
    function($productype_slug, $genre_slug) 
    {       
    }   
))->where('producttype_slug', '[A-Za-z\-]+')->where('genre_slug', '[A-Za-z\-]+');

Route::get('browse/{product_slug}', array(
    'as' => 'products.view_by_producttype', 
    function($product_slug)         
    {   
    }
))->where('product_slug', '[A-Za-z\-]+');

这样 - 如果路线与流派路线匹配 - 将首先使用它。

否则它将默认返回正常的产品路线。