【问题标题】:Filter record by using array - Laravel使用数组过滤记录 - Laravel
【发布时间】:2020-04-15 23:05:16
【问题描述】:

我有一个集合,我想使用数组根据“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_since_last_wallet_transaction,对吧
  • 是的,我得到了
  • 好吧,你想要的意思是 days_since_last_wallet_transaction > 2,更多记录或更少记录
  • 而你想与数组或单个值进行比较

标签: php mysql laravel laravel-query-builder


【解决方案1】:

考虑到您的数组下方:

$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');

【讨论】:

  • 使用原始查询使sql易受攻击,容易造成sql注入。
猜你喜欢
  • 2017-08-18
  • 2021-08-25
  • 2017-03-12
  • 2014-07-22
  • 2018-09-30
  • 2010-10-27
  • 1970-01-01
  • 2021-10-18
  • 2021-12-09
相关资源
最近更新 更多