Patrik Daňo
Patrik Daňo

Reputation: 11

Laravel ORM relationship returns null only on id > 1

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

App\User not returning null

But when the url is url.com/clanek/2 Only "null" is given.

Upvotes: 0

Views: 50

Answers (2)

A.A Noman
A.A Noman

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

Dilip Hirapara
Dilip Hirapara

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

Related Questions