【发布时间】:2020-02-27 06:38:38
【问题描述】:
我感觉卡住了。 :(
我希望能够执行不同的 SQL 查询,具体取决于我的表单中选择的过滤器:
//My initial query without any filters is this:
$dbQuery="SELECT * FROM \"interactions\" WHERE \"user_id\" = ".Auth::user()->getAttribute('id');
//Then depending on the selected filters the query may be any combination of the following:
if (request('contact_id')) $dbQuery.=" AND \"contact_id\" = ".request('contact_id');
if (request('product_id')) $dbQuery.=" AND \"product_id\" = ".request('product_id');
if (request('type')) $dbQuery.=" AND \"type\" LIKE \"%".request('type')."%\"";
if (request('description')) $dbQuery.=" AND \"description\" LIKE \"%".request('description')."%\"";
if (request('date')) $dbQuery.=" AND \"date\" >= ".request('date');
我有一个名为“Interaction”的类,它扩展了 Eloquent 模型,我需要能够执行上述查询或通过它表示相同的逻辑。
任何关于我如何实现这一目标的想法将不胜感激!
编辑: 感谢 Brice(我今天的个人英雄),这就是我的诀窍:
$query = Interaction::where('user_id', Auth::id());
$contact_id = request('contact_id');
$product_id = request('product_id');
$type = request('type');
$description = request('description');
$date = request('date');
if ($contact_id) $query->where('contact_id', $contact_id);
if ($product_id) $query->where('product_id', $product_id);
if ($type) $query->where('type', 'like', "%".$type."%");
if ($description) $query->where('description', 'like', "%".$description."%");
if ($date) $query->where('date', '>=', $date);
$interactions = $query->get();
return view('interactions.index',compact('interactions'));
【问题讨论】:
-
您在实现这一目标时遇到了哪些具体问题?你试过什么?附带说明一下,目前您的查询使您容易受到注入问题的影响 - 您应该在查询中使用绑定,而不是将数据值直接放入查询中。
-
嗨,zbee!我对 Eloquent 很陌生,对我来说有点模糊。我浏览了很多文章和文档,但似乎找不到合适的函数来表示上述逻辑。任何方向将不胜感激!我知道注射的问题,但这是我现在最不关心的问题。