php - 使用数组过滤记录 - Laravel

标签 php mysql laravel laravel-query-builder

我有一个集合,我想使用数组根据“days_since_last_wallet_transaction”过滤该集合。例如,我有一个数组 $day = array(2,4,6,8)。现在我想获取days_since_last_wallet_transaction在2,4,6,8中的记录。我认为我不能在 where 子句中使用“days_since_last_wallet_transaction”。这是我的查询:

Customer::select(
                'customers.id',
                'customers.wallet_amount',
                'customers.onesignal_id',
                'customers.phone_number',
                'customers.name',
                DB::raw('DATEDIFF(NOW(), max(wallet_transactions.created_at)) as days_since_last_wallet_transaction')
            )
            ->join('wallet_transactions', function ($join){
                $join->on('customers.id', '=', 'wallet_transactions.customer_id')
                ->where('wallet_transactions.amount', '>', 0);
            })
            ->groupBy('customers.id')
            ->where('customers.wallet_amount', '>', 0);

任何帮助都将非常感激。

最佳答案

考虑下面的数组:

$days = [2,4,6,8];

创建一个原始查询,如下所示(注意:您也可以在查询中写入此行)

$raw_query = '(DATEDIFF(NOW(), max(wallet_transactions.created_at))) IN  ('.implode(',',$days).')';

您的查询

Customer::select(
                'customers.id',
                'customers.wallet_amount',
                'customers.onesignal_id',
                'customers.phone_number',
                'customers.name',
                DB::raw('DATEDIFF(NOW(), max(wallet_transactions.created_at)) as days_since_last_wallet_transaction')
            )
            ->join('wallet_transactions', function ($join){
                $join->on('customers.id', '=', 'wallet_transactions.customer_id')
                ->where('wallet_transactions.amount', '>', 0);
            })
            ->where('customers.wallet_amount', '>', 0)
            ->havingRaw($raw_query)
            ->groupBy('customers.id');

关于php - 使用数组过滤记录 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59475982/

相关文章:

java - 当您键入时从 jcombobox 获取文本

python - Flask-SQLAlchemy 检查数据库服务器是否响应

php - 带有 id 变量的 Laravel 重定向路由将不起作用

php - Mysql查询CONCAT改变输出

php - 如何在 laravel 5 查询生成器上创建一个 mysql select 子查询

php - 将两个以上的查询合并为一个

拉拉维尔 : The payload is invalid

laravel - 如何在 laravel 5.6 中验证当前密码

php - 如何创建 .htaccess 文件以创建友好的 URL

php - 如何在我的表中搜索表单变量并在未找到时添加到表中,但如果找到则按用户指定的数量增加值?