Home > Back-end >  Laravel Link data queries and pagination
Laravel Link data queries and pagination

Time:08-01

How can I combine 3 requests into one to process it through "foreach" and display it with pagination?

$data['diamond_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 1)->orderByDesc('date_added')->get();
$data['vip_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 1)->orderByDesc('date_added')->get();
$data['default_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 0)->orderByDesc('date_added')->get();

CodePudding user response:

I wrote this query , give it a try

AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)
        ->where(function($query){
            $query->where('ad_diamond', '=', 1);
            $query->orWhere(function ($query) {
                $query->where('ad_vip', '=', 1);
                $query->where('ad_diamond', '=', 0);
            });
            $query->orWhere(function ($query) {
                $query->where('ad_vip', '=', 0);
                $query->where('ad_diamond', '=', 0);
            });
        })->orderByDesc('date_added')->paginate();

CodePudding user response:

As you use three separate queries and now you want to combine them, you can use all your queries in on query and handle that with orWhere in laravel like this:

AdModel::where(function (Builder $query){
        $query->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 1);
      })->orWhere(function(Builder $query){
        $query->where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 1)
      })->orWhere(function(Builder $query){
        $query->where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 0)
      })->orderByDesc('date_added')->paginate();
  • Related