我感觉卡住了。 :(
我希望能够执行不同的 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'));
最佳答案
我建议为此使用 Eloquent 查询构建器。
例如:
$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('type', 'like', "%$description%");
}
if ($date) {
$query->where('date', '>=', \Carbon\Carbon::parse($date));
}
$results = $query->get();
如果您有很多结果,您可能希望使用分页而不是如上所示同时获取所有结果。
关于php - Laravel 和 Eloquent - 应用不同的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651198/