mysql - Laravel - How to paginate here? -
i have code , want paginate $shares.
how can archive this?
$level = share::join('follows', 'shares.user_id', '=', 'follows.user_id') ->where('follows.follower_id', auth::user()->id) ->where('follows.level', 1) ->get(array('shares.*')); //get 10% of shares $count = share::count()/10; $count = round($count); $top10 = share::orderby('positive', 'desc') ->take($count) ->get(); $shares = $top10->merge($level); //get unique shares $unique = array(); $uniqueshares = $shares->filter(function($item) use (&$unique) { if (!in_array($item->id, $unique)) { $unique[] = $item->id; return true; } else { return false; } }); //order id $shares = $uniqueshares->sortby(function($share) { return -($share->id); }); return view::make('layout/main') ->with('shares', $shares);
lots of reudandant unnecessary codes here.
1st:
$level = share::join('follows', 'shares.user_id', '=', 'follows.user_id') ->where('follows.follower_id', auth::user()->id) ->where('follows.level', 1) ->get(array('shares.*'));
why taking all records discard later?
2nd:
$shares = $top10->merge($level);
why merging 2 arrays?
3rd:
$uniqueshares = $shares->filter(function($item) use (&$unique) { if (!in_array($item->id, $unique)) { $unique[] = $item->id; return true; } else { return false; }
});
you had wrote snippet because above in 2nd, merged 2 arrays yield duplicated entries. why merging?
4th:
//order id $shares = $uniqueshares->sortby(function($share) { return -($share->id); });
and here comes actual data want.
so let's recape
you need
- 10% of total shares
- order
positive
column - order amount of shares perhaps guessing.
to use inbuilt paginate()
, you'l need paginate()
that's must.
rest simple.
- count total result.
round(share::count()/10)
- put in
paginate()
1st arguement. - add order clause whichever necessary.
- looking @ code, doesn't will/should have duplicated data may haved added
distinct
,group by
clause.
use remember
in share::count()/10;
cache it. don't need run query on , on again.
and you're done.
Comments
Post a Comment