Vision Coderz
Vision Coderz

Reputation: 8078

How to retrieve data?

Post Model

class Post extends Model
{


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

    public function users()
    {
        return $this->belongsTo('App\User');
    }

    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }

Comment Model

class Comment extends Model
    {

    public function posts()
    {
        return $this->belongsTo('App\Post');
    }


   }  

Tag Model

class Tag extends Model
    {
    public function posts()
    {
        return $this->belongsToMany('App\Tag');
    }

User Model

class User extends Model
{


    public function posts()
    {
        return $this->hasMany('App\Post');
    }

Now my question is how i can access all comments that belong to post with commented username and tags belongs to that posts.Even i have confusion regarding tag relation because its having many to many relation

Thank you

Upvotes: 1

Views: 82

Answers (1)

Perdeep Singh
Perdeep Singh

Reputation: 492

Tag Model

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany('App\Tag');
         // Should this be return $this->belongsToMany('App\Post');
    }

Now solution for your question is "EAGER LOADING", let's see how we can use it for your situation.

1. All Comments

$commentsCollection = Comment::all();
// this will give us all comments.

2. Post With Comments and Users and tags

$postsCollection = Post::with('comments','users','tags')->get();
// this will give you collection of post with comments, users and tags. 
//So here you have all tags that belongs the a particular post.

Missing Relation

You are missing relation between Users and Comments.

Modified Comment Model

class Comment extends Model
{

    public function posts()
    {
        return $this->belongsTo('App\Post');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

Modified USER Model

class User extends Model
{


    public function posts()
    {
        return $this->hasMany('App\Post');
    }

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

Upvotes: 1

Related Questions