I have a leaderboards and leaderboard_scores table.
leaderboard_scores has columns: id, leaderboard_id, player_id, score.
In Leaderboard model, I defined a hasMany relationship with LeaderboardScore:
public function scores()
{
return $this->hasMany('App\LeaderboardScore')->orderBy('score', 'desc');
}
Now I want to get the ranking of a player in a particular leaderboard.
So in controller, I do a loop to find the position given a player_id:
$score = $leaderboard->scores;
$scoreCount = $scores->count();
$myScore = $scores->where('player_id', $request->query('player_id'));
if ($myScore) { // If got my score
$myRank = 1;
for ($i = 0; $i < $scoreCount; $i++) {
if ($scores[$i]->player_id == $request->query('player_id')) {
$myRank = $i + 1;
break;
}
}
// Output or do something with $myRank
}
It works fine, but I am worried about the performance, when I have hundred thousand of players and they constantly getting their ranking. The for loop seems not a good option.
Should I use raw database query? Or any better idea?
Here some ideas
Instead of calculating ranks each time you get request, then loop through all data. you can just store players rank either in database or cache. You only need to calculate them when new player added/deleted or score changed.
Check For Caching:
https://laravel.com/docs/5.4/redis
if you still want to calculate it everytime you can use mysql rank function which is more optimized than a primitive loop
Mysql Rank : http://www.folkstalk.com/2013/03/grouped-rank-function-mysql-sql-query.html
Related
As I'm trying to implement charts into Backpack for Laravel, I been stuck for a few hours on this problem. The following script gets the number of users created for each day and appends them to an array that is then shown on the charts.
for ($days_backwards = 7; $days_backwards >= 0; $days_backwards--) {
// Could also be an array_push if using an array rather than a collection.
$users = Users::whereDate('created_at', today()->subDays($days_backwards))->count();
$user[] = $users;
}
Every iteration of the loop adds a number to the array (or is it a collection??) so something like [2,5,10,9,...].
I would rather like to get the total amount of users that ever registered, incrementally for each day, so that the result would be someting like [2,7,17,26,...].
I figured I could add each iteration with array_sum() but it's not working. Is it an array anyways? Is there a way to append to this list the sum to its previous?
Well I kind of figured out!
$sum = 0;
for ($days_backwards = 7; $days_backwards >= 0; $days_backwards--) {
$users = Users::whereDate('created_at', today()->subDays($days_backwards))->count();
$sum = $sum + $users;
$user[] = $sum;
}
It works!
i want to sum profit by activating multiple plans. I am using get() with foreach but it returns only last row data. not all rows data. its strange while on other queries it returns all rows data.
for example, I have 2 deposits one 25$ and 2nd 35$ its returns 35$ data only.
i tried with
$deposits = Deposit::get();
but it is not working I went to increase rows to 12 but still, it returns data of 12th row only
$deposits = Deposit::where('account_id', $account->id)->where('status',1)->get();
foreach($deposits as $pn) {
$plans = package::where('id',$pn->plan)->first();
$percent = $plans->min_amount * $plans->percent/100;
}
After discussing in chat, the real problem is adding up the percentages during looping :
$percent = 0;
foreach ($deposited as $de) {
$pack = Package::Where('id', $de->plan)->first();
$log = Deposit::Where('id', $de->id)->first();
$percent = $percent + ($log->amount * $pack->percent / 100);
}
I have a Collection of collection.
I would like to get the biggest collection inside the collection.
I wrote a function that works well, but I'm pretty sure it can be done much quicker:
private function getMaxFightersByEntity($userGroups): int
{
$max = 0;
foreach ($userGroups as $userGroup) { // $userGroup is another Collection
if (count($userGroup) > $max) {
$max = count($userGroup);
}
}
return $max;
}
I'm quite sure there is a better way managing collection, but don't really know it.
Anyone has a better solution???
You can sort the collection by the count of the inner collections, and then just take the first item (largest group).
// sortByDesc: sort the groups by their size, largest first
// first: get the first item in the result: the largest group
// count: get the size of the largest group
return $userGroups
->sortByDesc(function ($group) {
return $group->count();
})
->first()
->count();
It won't be "quicker" than your current solution in execution time, but it is written to take advantage of the functions provided by collections.
I have three tables; user, car and user_x_car. user_x_car holds users who own car; user_id and car_id are stored. I want to get users who don't own a car as follows:
$car_owner = $this->db->select()->from('user_x_car')->get()->result();
for ($i = 0; $i < count($car_owners); $i++)
$car_owner_id[$i] = $car_owner[$i]->user_id;
$non_car_owner = $this->db->select()->from('user')->where_not_in('id', $car_owner_id)->get()->result();
I get what I want, however, is there any way to bypass the for loop in the middle which creates and array of id's selected in the first select. Is there any way to get array of selected user_ids directly?
you can do it by two queries like
first one get all ids from user_x_car table
$temp1=array();
$temp=$this->db->distinct()->select('user_id')->get('user_x_car')->result_array();
then from user table fetch those users who have no cars
foreach($temp as $each)
{
array_push($temp1,$each['user_id']);
}
$rs=$this->db->where_not_in('id',$temp1)->get('user');
if($rs->num_rows()>0)
{
$data=$rs->result_array();
print_r($data);die;
}
$data will print all users who have no car. Please let me know if you face any problem.
function get_unread_notifications_ids()
{
//get unread notifications ids
$this->db->select('GROUP_CONCAT(fknotification_id) as alll');
$this->db->from("te_notification_status_tbl");
$this->db->where('read_status',0);
$ids=$this->db->get()->row();
return $idss=str_replace(",","','",$ids->alll);
}
and second function like this:
function get_unviewed_photos_events(){
$idss = $this->get_unread_notifications_ids();
$this->db->select('img.*',False);
$this->db->from("te_notifications_tbl notif");
$this->db->join('te_images_tbl img','img.id=notif.reference_id','LEFT OUTER');
$this->db->where("notif.id IN('".$idss."')");
$rslt = $this->db->get()->result_array();
return $rslt;
}
Query
$non_car_owner = $this->db->query('SELECT user.*
FROM user LEFT JOIN user_x_car ON user_x_car.id=user.id
WHERE table2.id IS NULL')->result();
Here users who are not on the table user_x_car
foreach($non_car_owner as $user){
echo $user->user_id;
}
I'm using codeigniter and the pagination class. This is such a basic question, but I need to make sure I'm not missing something. In order to get the config items necessary to paginate results getting them from a MySQL database it's basically necessary to run the query twice is that right?
In other words, you have to run the query to determine the total number of records before you can paginate. So I'm doing it like:
Do this query to get number of results
$this->db->where('something', $something);
$query = $this->db->get('the_table_name');
$num_rows = $query->num_rows();
Then I'll have to do it again to get the results with the limit and offset. Something like:
$this->db->where('something', $something);
$this->db->limit($limit, $offset);
$query = $this->db->get('the_table_name');
if($query->num_rows()){
foreach($query->result_array() as $row){
## get the results here
}
}
I just wonder if I'm actually doing this right in that the query always needs to be run twice? The queries I'm using are much more complex than what is shown above.
Unfortunately, in order to paginate you must know how many elements you are breaking up into pages.
You could always cache the result for the total number of elements if it is too computationally expensive.
Yeah, you have to run two queries, but $this->db->count_all('table_name'); is one & line much cleaner.
Pagination requires reading a record set twice:
Once to read the whole set so that it can count the total number records
Then to read a window of records to display
Here's an example I used for a project. The 'banner' table has a list of banners, which I want to show on a paginated screen:
Using a public class property to store the total records (public $total_records)
Using a private function to build the query (that is common for both activities). The parameter ($isCount) we pass to this function reduces the amount of data the query generate, because for the row count we only need one field but when we read the data window we need all required fields.
The get_list() function first calls the database to find the total and stores it in $total_records and then reads a data window to return to the caller.
Remember we cannot access $total_records without first calling the get_list() method !
class Banner_model extends CI_Model {
public $total_records; //holds total records for get_list()
public function get_list($count = 10, $start = 0) {
$this->build_query();
$query = $this->db->get();
$result = $query->result();
$this->total_records = count($result); //store the count
$this->build_query();
$this->db->limit($count, $start);
$query = $this->db->get();
$result = $query->result();
return $result;
}
private function build_query($isCount = FALSE) {
$this->db->select('*, b.id as banner_id, b.status as banner_status');
if ($isCount) {
$this->db->select('b.id');
}
$this->db->from('banner b');
$this->db->join('company c', 'c.id = b.company_id');
$this->db->order_by("b.id", "desc"); //latest ones first
}
And now from the controller we call:
$data['banner_list'] = $this->banner_model->get_list();
$config['total_rows'] = $this->banner_model->total_records;
Things get complicated when you start using JOINs, like in my example where you want to show banners from a particular company! You may read my blog post on this issue further:
http://www.azmeer.info/pagination-hitting-the-database-twise/