首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel -在routes.php中使用'where‘查询模型

Laravel -在routes.php中使用'where‘查询模型
EN

Stack Overflow用户
提问于 2013-12-17 18:49:30
回答 3查看 2.2K关注 0票数 2

我希望扁平我的搜索引擎优化目的电商商店我的路线。

我想创建以下路由:

代码语言:javascript
复制
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry']);
Route::get('/{category}, ['uses' => 'Store\ProductController@browseCategory']')

countrycategory必须是动态的。

我想知道下面这样的事情是否可能发生?最好的实现方式。

代码语言:javascript
复制
// Route 1
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
    ->where('country', ProductCountry::select('slug')->get());

// Route 2
Route::get('/{category}', ['uses' => 'Store\ProductController@browseCategory'])
    ->where('category', ProductCategory::select('slug')->get());

示例路由:

代码语言:javascript
复制
/great-britain should be routed via Route 1
/china         should be routed via Route 1

/widgets       should fail route 1, but be routed via Route 2 because 
               widgets are not in the product_country table but are in 
               the product_category table

我知道我可以用可能的国家/地区硬编码我的路由:

代码语言:javascript
复制
Route::get('/{country}', ['uses' => 'Store\ProductController@browse'])
    ->where('country', 'great-britain|china|japan|south-africa');

然而,这是笨拙和乏味的。我想从数据库中得到国家的名单。

EN

回答 3

Stack Overflow用户

发布于 2013-12-17 20:41:41

我将这样做,我选择国家/地区模型,因为您需要缓存的名称较少:将列表(‘models+’)更改为country name列

代码语言:javascript
复制
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', implode('|',ProductCountry::select('slug')->lists('name')));

它所做的是选择所有国家/地区的名称,并将它们作为数组返回,如下所示

代码语言:javascript
复制
 ('usa','england','thailand') 

并使用内爆与'|‘作为胶水返回以下内容:

代码语言:javascript
复制
usa|england|thailand

所以你的最终路线是这样的:

代码语言:javascript
复制
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', 'usa|england|thailand');
票数 3
EN

Stack Overflow用户

发布于 2013-12-17 19:09:18

好的,在查看完更新后的问题之后,您需要在各自的模型中创建一个方法,以便将所有可用的slug与|字符连接起来,这样您就可以调用如下代码:

代码语言:javascript
复制
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
     ->where('country', ProductCountry::getSlugs());

这会像你的例子中一样返回‘great-britain|china|日本|south-south’,只是你不需要写出来。

但是,我强烈建议您为路由提供更多的内容,/country/{country}或/category/{category},否则会令人困惑,并且URI结构通常是这样的,这样用户就可以准确地看到他们所在的位置。

票数 0
EN

Stack Overflow用户

发布于 2013-12-17 19:44:22

您需要路由过滤器来实现这一点。

将以下代码放入filters.phproute.php文件中

代码语言:javascript
复制
Route::filter('country', function()
{

    $country = Country::where('slug', Route::input('country'))->first();
    if(  ! $country) {
        dd("We do not support this country");
            // Redirect::route('home');
    }

});

最后是你的路线:

代码语言:javascript
复制
Route::get('country/{country}', array('before' => 'country', 'uses' => 'Store\ProductController@browseCountry'));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20632149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档