Reputation: 11
I have recently found a problem. I have 2 models, Articles and Users. i have defined the models relationships like this.
User.php
public function articles()
{
return $this->hasMany(Articles::class,'written_by');
}
Article.php
public function writer()
{
return $this->hasOne(User::class, 'id');
}
The problem is the relationship is accessible only whenever reading the article with id 1
url.com/clanek/1
But when the url is url.com/clanek/2 Only "null" is given.
Upvotes: 0
Views: 50
Reputation: 5270
You have to change like this
User.php
public function articles(){
return $this->hasMany(Article::class,'written_by','id');
}
Article.php
public function writer(){
return $this-> belongsTo(User::class);
}
Upvotes: 0
Reputation: 15296
change the relation as below.
User.php
public function articles()
{
return $this->hasMany(Articles::class,'written_by','id');
}
and in Article.php it'll be belongsTo
public function writer()
{
return $this->belongsTo(User::class,'written_by','id');
}
Upvotes: 2