Search code examples
phparrayslaravelobjectlimit

Bifurcate data which I get from an Object and having used take() in Laravel?


What I need: I have to get exactly 25 data from a query, and for that I have used take(25), which gives me 25 data in an object because I am passing $data as an object there.

The problem is, that I have to get exact 7 data between the price(one of my columns) range $20-$25, and the other 18 data should be greater than $25, and I am unable to bifurcate the data that I receive as an object.

What I have done till now: I have tried a lot of things and implemented a lot of functionalities using different functions like: array_chunk, array_slice, array_merge, etc. But still, I am not able to get the data in the format that I need.

I hope someone comes up with an appropriate solution. And for that, Thanks in advance.

$data =  DB::table('websites')->selectRaw('websites.*,ads.user_id,ads.meta_value,CASE WHEN ads.meta_value THEN (CEILING(((ads.meta_value*websites.publishing_price/100)+websites.publishing_price ))) ELSE (CEILING(((0*websites.publishing_price)+websites.publishing_price))) END As original_publishing_price,CASE WHEN ads.meta_value THEN (select COUNT(order_attributes.website_id) from order_attributes WHERE order_attributes.website_id = websites.id AND order_attributes.status = 6 AND DATE(`order_attributes`.`created_at`) >= "' . $first_day_prev . '" AND DATE(`order_attributes`.`created_at`) <= "' . $last_day_prev . '" ) END AS total_orders')
                ->join('admin_settings as ads', function ($join) {
                $join->where('ads.user_id', '=', '1')->where('ads.meta_key', '=', "str_commission");
                })
                ->join('users', 'users.id', 'websites.publisher_id')
                ->where('websites.status', Websites::STATUS_APPROVED)
                ->where('users.vacation_mode', '0')
                ->where('websites.is_process', '=', websites::PROCESS_COMPLETE)
                ->where('websites.deleted_at', null)
                ->where('users.is_active', 0)
                ->whereBetween('websites.publishing_price',[ '15', '20'])
                ->take(25);

Solution

  • You can make the Union of your data by taking out separately by query first 7 websites and merge it second query with your 18 websites. Short example:

    $seven = DB::table('websites')
    ...
    ->whereBetween('websites.publishing_price',[ '20', '25'])
    ->take(7);
    
    $result  = DB::table('websites')
    ...
               where('websites.publishing_price', '<=', 25)
               ->limit(18)
               ->unionAll($seven)
               ->get();