Reputation: 28795
In Laravel (v5.7.12), I have two models - User
and Project
.
A user has an id
and can have many projects. A project has an owner_id
.
I can't seem to configure the relationship correctly. In my user model, I have:
/**
* Get the projects associated with the user.
*/
public function projects()
{
$this->hasMany('\App\Project', 'owner_id', 'id');
}
In my project model, I have:
/**
* Get the owner associated with the user.
*/
public function owner()
{
$this->belongsTo('\App\User', 'id', 'owner_id');
}
But calling either $user->projects()
or $project->owner()
returns null
.
How should I configure my non-standard relationship keys?
Upvotes: 1
Views: 35
Reputation: 758
You forgot to return the method:
public function projects()
{
return $this->hasMany('\App\Project', 'owner_id');
}
Do this also for the second one:
public function owner()
{
return $this->belongsTo('\App\User', 'owner_id');
}
Upvotes: 3