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();
Or could it be that foreign key on 'players' table has to be named differently (dbnation_id ? )?
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community