bootstrapguru's avatar

Create temporary table and assign it to model

I have a model called SaleTemp which needs a temporary table sales_temp that creates an on the fly by joining 5 or more other tables like sales, sale_items, customers, sale_payments, sale_taxes. I have added the raw query to the construct method of the model to create a temporary table before the model initializes, but with that approach, when I try to get sales by pagination it shows that query is executed more than 30 times and just to get the 100 results from 15K rows of table, it is taking more than 29s. So to fix this, I have created a couple of methods createTable and destroyTable to create and delete the table before I try to fetch and after I get the data like below.

        $saleTemp = new SaleTemp($params);
        $saleTemp->createTable($params);
        
        $summaryData = $saleTemp->select([
                                DB::raw('sum(sub_total) as sub_total'),
                                DB::raw('sum(tax) as taxes'),
                                DB::raw('sum(total) as total'),
                                DB::raw('sum(profit) as profit'),
                                DB::raw('count(*) as count'),
                              ])
                            ->get()->toArray();
        $saleTemp->deleteTable();

I know this solves a problem to some extent but I am not sure if this is the right approach, I hate to call the method before and after trying to fetch the data and also I lose many laravel features to run on the model. Is there any way that I could do it better? Please let me know if I need to explain it better.

0 likes
1 reply
rthunoli's avatar

Try Sushi Eloquent's missing "array" driver.

Please or to participate in this conversation.