Php 如何将模型绑定到Laravel4中的查询字符串参数?
我知道可以将模型绑定到Laravel中的route参数,但是有没有一种方法可以将它们绑定到可选的查询字符串参数 例如,给定的URL为:Php 如何将模型绑定到Laravel4中的查询字符串参数?,php,laravel,laravel-4,Php,Laravel,Laravel 4,我知道可以将模型绑定到Laravel中的route参数,但是有没有一种方法可以将它们绑定到可选的查询字符串参数 例如,给定的URL为: http://myapi.example.com/products?category_id=345 使用以下路线的: Route::resource('products', 'ProductController'); 有没有一种方法可以将可选的查询字符串参数category\u id绑定到我们的类别模型,这样它就可以自动注入到ProductControlle
http://myapi.example.com/products?category_id=345
使用以下路线的:
Route::resource('products', 'ProductController');
有没有一种方法可以将可选的查询字符串参数
category\u id
绑定到我们的类别模型,这样它就可以自动注入到ProductController中?目前,我认为资源路由不可能做到这一点,因为它会自动将一些RESTful路由映射到给定的资源(根据。如果您想要具有可选参数的路由,则必须使用其他一些选项在Laravel中写入路由,并确保在声明资源控制器之前放置路由。这是可能的,但并非如您的问题所示
有没有办法绑定可选的查询字符串参数category\u id
到我们的类别模型,以便它可以自动注入到
产品控制器
将查询字符串参数绑定到产品模型,而不是类别模型
下面是一种基于查询字符串输入将过滤数据发送到视图的快速而肮脏的方法。这将过滤类别关系
可能会有语法错误,因为我只是很快地敲出了一个答案——但这个概念是可行的
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方法
事实上,我很高兴能在我的一个类似问题中帮助他回答,他向我介绍了newQuery方法