2

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

例如,给定一个 URL:

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

使用以下路线:

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

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

4

2 回答 2

0

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

于 2013-10-21T14:41:44.660 回答
0

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

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

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

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

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

产品控制器

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:如果通过查询关系存在关系,则选择行

于 2013-12-17T09:50:11.293 回答