Support the ongoing development of Laravel.io →
posted 11 years ago
Eloquent

I have a table ranks as

position	player_id
1			77
2			99
3			12

and one more table players as

id	name	email	
====================
12	Joe		joe@gmail.com
77	Vik		vic@gmail.com
99	mark	markk@ymail.com
100   noah nh@gg.com

now I want to fetch all the players according to their ranks, Any suggestions how can I relate table ranks to players in Eloquent. I know using normal sql queries It can be done easily ,but I just want to it Laravel way.

Note: all players are not ranked, ranking is only for top 100 players (Edited after @crhayes reply)

Last updated 3 years ago.
0

Have you read through the documentation? It's outlined clearly there.

<?php

class Player extends Eloquent
{
	public function rank()
	{
		return $this->hasOne('Rank');
	}
}

class Rank extends Eloquent
{
	public function player()
	{
		return $this->belongsTo('Player');
	}
}
Last updated 3 years ago.
0

Thanks for suggestion @crhayes, I have made a edit in question, that not all players are ranked I should have made it clear first hand only sorry.

Last updated 3 years ago.
0

If not all the players are ranked then the ones that dont have a rank, the relationship should not return anything... You can check for this.

Last updated 3 years ago.
0

manishk3008 said:

Thanks for suggestion @crhayes, I have made a edit in question, that not all players are ranked I should have made it clear first hand only sorry.

You can do one of two things:

// Get all of the ranks with the associated player
$ranks = Rank::with('player')->get();
// Get all players that have a rank
$players = Player::has('rank')->get();
Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.