2
 public function comments()
  {
    return $this->hasMany('App\Comment');
  }

in the model userPost stores the posts;the foreign key is post_id and primary key is id.i am new in laravel

2 Answers 2

2

link for laravel one to many relationship documentation

hasMany('App\Comment', 'foreign_key', 'local_key');
Sign up to request clarification or add additional context in comments.

Comments

0

If your Model would Post instead userPost it would work, because laravel treat foreign key as model name uderscore and id means it search for postUser_id but you have post_id, so you need to explicitly pass as second parameter

return $this->hasMany('App\Comment', 'post_id', 'id'); 

//return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

Check the docs says

Eloquent will take the "snake case" name of the owning model and suffix it with _id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.