Filament Table custom query

use Illuminate\Support\Facades\DB;

$results = [
    ['id' => 1, 'name' => 'abu'],
    ['id' => 2, 'name' => 'ali'],
    ['id' => 3, 'name' => 'ahmad'],
];

// Convert array to unioned SELECTs
$selects = collect($results)->map(function ($row) {
    return DB::table(DB::raw("(SELECT '{$row['id']}' as id, '{$row['name']}' as name)"));
});

// Merge with UNION
$subQuery = $selects->reduce(function ($carry, $query) {
    return $carry ? $carry->unionAll($query) : $query;
});

// Then use fromSub
$query = DB::query()->fromSub($subQuery, 'docs_tpd')->get();

Simplified

 ->query(
                function () use ($month, $year) {
                    // Fetch and merge data

                    // dd(DB::connection('ripdbsp')->table('aainsclm')->whereMonth('opday', $month)->whereYear('opday', $year)->get());

                    $results = collect([
                        ...DB::connection('ripdbsp')->table('aainsclm')
                            ->leftJoin('clmr', 'aainsclm.actno', '=', 'clmr.actno')->select([
                                'aainsclm.id',
                                'aainsclm.actno',
                                'clmr.prodcd',
                                'aainsclm.id1',
                                'aainsclm.name',
                                'aainsclm.inscomcd'

                            ])->whereMonth('aainsclm.opday', $month)->whereYear('aainsclm.opday', $year)->get(),
                        ...TpdReportModel::select([
                            'id',
                            'actno',
                            'prodcd',
                            'id1',
                            'name',
                            'inscomcd'
                        ])->whereMonth('created_at', $month)->whereYear('created_at', $year)->get(),
                    ])->unique('actno')->values();


                    // Convert to subquery using UNION ALL
                    $subQuery = $results->map(function ($row) {
                        $selectParts = collect($row)->map(function ($value, $key) {
                            $escaped = addslashes(trim((string) $value));
                            return "'{$escaped}' AS `{$key}`";
                        })->implode(', ');

                        return DB::connection('ripdbsp')->query()->selectRaw($selectParts);
                    })->reduce(fn($carry, $query) => $carry ? $carry->unionAll($query) : $query);

                    return Aainsclm::query()->fromSub($subQuery, 'aainsclm');
                }

            )

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *