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)
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');
}
}
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.
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.
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();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community