这是可能的,但不是你的问题。
有没有办法将我们的可选查询字符串参数 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:如果通过查询关系存在关系,则选择行