【问题标题】:How to bind model to query string parameter in Laravel 4?如何在 Laravel 4 中将模型绑定到查询字符串参数?
【发布时间】:2013-12-17 17:58:15
【问题描述】:

我知道你可以在 Laravel 中将模型绑定到路由参数,但是有没有办法可以将它们绑定到可选的查询字符串参数。

例如,给定一个 URL:

http://myapi.example.com/products?category_id=345

使用以下路线:

Route::resource('products', 'ProductController');

有没有办法将我们的可选查询字符串参数category_id绑定到我们的Category模型中,从而可以自动注入到ProductController中?

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    目前,我认为资源路由不可能做到这一点,因为它会自动将一些 RESTful 路由映射到给定资源(根据 docs)。如果你想要一个带有可选参数的路由,你将不得不使用其他一些选项在 Laravel 中编写路由,并确保在声明资源控制器之前放置它。

    【讨论】:

      【解决方案2】:

      这是可能的,但不是你的问题。

      有没有办法绑定我们的可选查询字符串参数 category_id 到我们的 Category 模型中,以便它可以自动注入 产品控制器?

      您将查询字符串参数绑定到产品模型,而不是类别模型。

      下面是一种基于查询字符串输入将过滤数据发送到视图的快速而肮脏的方法。这会过滤类别关系。

      可能存在语法错误,因为我刚刚快速敲出了一个答案 - 但这个概念有效。

      产品控制器

      class ProductController extends BaseController
      {
          protected $productModel;
          function __construct(Product $productModel)
          {
              $this->$productModel = $productModel;
          }
      
          public function index()
          {
              $products = $this->productModel
                  ->join('categories', 'categories.id', '=', 'products.category_id');
                  ->select(// select your columns)
      
              $filterCategory = Input::get('category_id');
      
              if ($filterCategory)
              {
                  ->where('category_id', '=', $filterCategory)
              } 
      
              $data = $products->get();
      
              return View::make( 'shop.product.index')->with($data);
          }
      }
      

      更好的解决方案是将此代码从控制器中抽象出来并覆盖模型的 newQuery 方法。

      事实上,很高兴 Help 在我的一个类似问题中的回答向我介绍了 newQuery 方法。 Laravel 4: Select row if a relation exists by querying relation

      【讨论】:

        猜你喜欢
        • 2016-12-15
        • 1970-01-01
        • 2018-04-30
        • 2020-09-02
        • 1970-01-01
        • 2012-03-23
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多