2

I have four models post postcomment postcategory and category I want to get all the posts with their comments and categories. postcategory table having post_id and category_id while category table has id and category_name fields in it

I am able to get record with my query like below

Array
(
[0] => Array
    (
        [id] => 1
        [post_title] => My First Post
        [postcategory] => Array
            (
                [0] => Array
                    (
                        [post_id] => 1
                        [category_id] => 1
                    )
            )

        [postcomment] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [post_id] => 1
                        [postcomment] => first comment of first post
                    )
            )
      )
)

I am able to get category_id from postcategory model as you can see in result array, How can I have category_name in this situation

Models

post Model

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


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

postcategory Model

public function post()
{        
    return $this->belongsTo(post::class);
}

postcomment Model

public function post()
{        
    return $this->belongsTo(post::class);
}

category Model

public function post()
{        
    return $this->belongsTo(post::class);
}

Query

$posts = post::with(['postcategory', 'postcomment','category'])->get();
mohsin ali
  • 31
  • 3

0 Answers0