laravel 如何过滤包含“orWhereHas”和“OrWhereIn”的Eloquent查询?

ukxgm1gy  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(94)

我在Eloquent中有一个查询,我想按日期过滤,但有一个“WhereHas”或“WhereIn”不再过滤它们。如何解决我的问题?

public static function filterForTransactions(Request $request, MarketAgreement $v_teleco, AgreementEnergia $v_energia) {

        $v_teleco = $v_teleco->newQuery();

                    $v_teleco->where('user_id_inversor', \Auth::user()->id)
                    ->orWhereHas('market_transaction', function($query){
                        $query->where('user_id_subaccount', \Auth::user()->id);
                    })
                    ->orWhereIn('user_id', [$ids]);

        if ($request->has('from') && $request->has('to') && $request->input('from') != null && $request->input('to') != null) {

            $from = \Carbon\Carbon::parse($request->from)
            ->startOfDay()
            ->toDateTimeString();

            $to = \Carbon\Carbon::parse($request->to)
            ->endOfDay()
            ->toDateTimeString();

                
            $v_teleco->whereBetween('created_at', [$from, $to]);

        }

        return $v_teleco->orderBy('updated_at', 'desc')->get();

}
ilmyapht

ilmyapht1#

关于你的代码有几件事要提一下

public static function filterForTransactions(Request $request, MarketAgreement $v_teleco, AgreementEnergia $v_energia)
    {
        /** @var Illuminate\Database\Eloquent\Builder $v_teleco */
        $v_teleco = $v_teleco->newQuery();
        // when you want to modify builder object you need to overwrite it
        $v_teleco = $v_teleco->where('user_id_inversor', \Auth::user()->id)
            ->orWhereHas('market_transaction', function ($query) {
                $query->where('user_id_subaccount', \Auth::user()->id);
            })
            ->orWhereIn('user_id', [$ids]); // where do you get $ids?

        if ($request->has('from') && $request->has('to') && $request->input('from') && $request->input('to')) {
            $from = \Carbon\Carbon::parse($request->from)
                ->startOfDay()
                ->toDateTimeString();
            $to = \Carbon\Carbon::parse($request->to)
                ->endOfDay()
                ->toDateTimeString();
            // same here
            $v_teleco = $v_teleco->whereBetween('created_at', [$from, $to]);
        }

        return $v_teleco->orderBy('updated_at', 'desc')->get();
    }

这样它看起来很好,所以如果它仍然不工作,请提供更多的细节

相关问题