php - Laravel 和 Eloquent - 应用不同的过滤器

标签 php sql laravel eloquent

我感觉卡住了。 :(

我希望能够执行不同的 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/

相关文章:

php - 调用非对象成员函数

c# - SQL Server 中的 GUID

sql - 需要 Oracle sql 查询来对日期进行分组

python - sqlalchemy.exc.MultipleResultsFound : Multiple rows were found when exactly one was required

php - 具有多个 where orwhere 和内部连接的 laravel mysql 查询

php - 如果不存在 PHP session ,则禁用页面上的所有输入按钮

javascript - Ajax 无法从 php 文件加载内容

javascript - 需要使用 fetch 从(laravel api)获取数据,然后将其解析到另一个函数

php - 同一台服务器上的 Laravel 4.2 环境

php - 使用自动建议 jQuery 插件的多标签