【问题标题】:Laravel 4.x, routing multiple related parametersLaravel 4.x,路由多个相关参数
【发布时间】:2014-09-24 23:18:28
【问题描述】:

带有类似的链接

http://example.com/catalog/slug/brand/product

和类似的路线

Route::get('catalog/{slug}/{brand}/{product}', 'Controller@method');

并且知道每个参数都有一个检查参数是否存在的绑定。

我有 3 张桌子:

Catalogs
    id | catalog_slug
Brands
    id | brand_slug
Products
    id | product_slug | brand_id | catalog_id

如何检查这些参数是否相关(按产品表)而不是它们仅存在于路线中?它工作正常,但我想确保它们彼此相关。

【问题讨论】:

  • 您是如何定义CatalogsBrandsProducts 模型之间的关系的?
  • 如果定义了关系,您应该提供更多信息以及处理发生的控制器方法。

标签: php laravel laravel-routing


【解决方案1】:

在您的方法中添加此代码:

$parameters = Route::current()->parameters();
$areRelated = DB::table('Products')
            ->join('Brands','Brands.id','=','Products.brand_id')
            ->join('Catalogs','Catalogs.id','=','Products.catalog_id')
            ->where('Catalogs.catalog_slug',$parameters['slug'])
            ->where('Brands.brand_slug',$parameters['brand'])
            ->where('Products.product_slug',$parameters['product'])
            ->count();
if(! areRelated )
    App::abort(404);

【讨论】:

    【解决方案2】:

    使用route binding

    Route::get('catalog/{catalog}/{brandByID}/{productByID}', 'Controller@method');
    

    在 bindings.php 中(在 globals.php 末尾创建并包含)

    Route::model('catalog', 'Catalog'); // now using {catalog} in route will look up the catalog instance by ID and pass it to the controller method instead of the ID.
    
    // use custom resolver for brand parameter, use {brandByID} in route
    Route::bind('brandByID', function ($brandID, $route) {
        //Get the catalog from the catalog bind function
        $catalog = $route->parameter('catalog');
        $brand = $catalog->brands()->findOrFail($brandID); // fails if catalog does not have this brand
        return $brand;
    }
    

    对产品做同样的事情,但添加第二个检查。您还需要在目录模型中正确设置品牌关系,例如

    public function brands()
    {
        return $this->belongsToMany('Brand');
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-08
      • 2013-11-24
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2014-10-13
      • 2014-08-10
      • 2016-12-29
      相关资源
      最近更新 更多