Support the ongoing development of Laravel.io →
Database Eloquent

Hi, I have a simple scenario here that is bugging me. There are two models:

class DbNation extends Eloquent {
    
    protected $table = 'db_nations';
    
    public function players() 
    {
        return $this->hasMany('Player');
    }
}

which is a list of nations with ids

class Player extends Eloquent {

    public function dbnation()
    {
        return $this->belongsTo('DbNation');
    }
}

Table 'players' has column 'nation_id' that is a FK to 'db_nations'.'id'

And now when I'm trying to get nation of a player in my view with $player->dbnation->name, $player->dbnation isn't returning anything. Could it be because my table name is different than my class name? How do I get this to work (without changing table name if possible)? This works though: DbNation::where('id', '=', $player->nation_id)->get();

Last updated 3 years ago.
0

Or could it be that foreign key on 'players' table has to be named differently (dbnation_id ? )?

Last updated 3 years ago.
0

You need to do it as follows:

class Player extends Eloquent {

    public function dbnation()
    {
        return $this->belongsTo('DbNation', 'nation_id');
    }

}

The second parameter in the "belongsTo" function will define the local key for the relationship.

Last updated 3 years ago.
0

aka, rtfm.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

akalajzi akalajzi Joined 9 Feb 2014

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.