這是可能的,但不是你的問題問。
是否有我們的可選查詢字符串參數綁定的方式CATEGORY_ID 我們的分類模型,以便它可以自動注入 的ProductController的?
將查詢字符串參數綁定到產品模型,而不是類別模型。
下面是基於查詢字符串輸入將過濾數據發送到視圖的一種快速而髒的方法。這將過濾類別關係。
由於我只是很快地敲出答案,可能會出現語法錯誤 - 但這個概念很有用。
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方法的類似問題之一。 Laravel 4: Select row if a relation exists by querying relation