0

1 year agoby Vamsi Krishna

Giving eloquent relationship

Hi, i have doubt how to give eloquent relationship in follow tables. i have 3 tables Users, Posts(contains user foreign key), Comments

in user model i.e user.php i have written this hasMany(Posts::class)

in posts model i.e posts.php belongsTo(User::class)

user and posts models have been connected.

comments table will be storing only comment detail nothing else.

now one another table is there which stores foreign keys of all above three tables.

now how can i get all the posts of logged in user along with all comments on that posts with help of eloquent.

without eloquent i can do the stuff but with eloquent i am not getting.

0

Vamsi Krishna replied 1 year ago

0

correct i did like this only thanx for your response:). I watch all your videos in bitfumes channel liked all of them. specially all the stuff realted to laravel are good.

22

Sarthak replied 1 year ago

0

Hey, you don't need 4th table. Just connect comments table and post table like in post model

public function comments()
{
return $this->hasMany(Commant:class);
}

and reverse on comment. So lets say you are looged in, then you can get posts of logged in user like

auth()->user()->posts;

Now to while using posts you can get comments for single post like

$post->comments;
Ask Question
Most Visited
Categories