Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel eloquent hasmanythrough get count

I use laravel 9.x

I am trying to get the count of the Content_hashtag and combine it into the tag,

I have 4 tables like the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 Chapter
 bp_chapter_id,
 bp_chapter_name,

 Section
 bp_section_id,
 bp_chapter_id,
 bp_tag_id,

 Content_hashtag
 bp_ch_id, 
 bp_tag_id, 
 bp_content_id

 Hashtag
 bp_tag_id,
 bp_hashtag_name

At the model , i have using hasmanythrough like following:


Chapter Model : 

    public function Tag()
    {
        return $this->hasManyThrough(Tag::class, Section::class, 'bp_chapter_id','bp_tag_id','bp_chapter_id','bp_tag_id');
    }

Controller: 
   $sections= chapter::with('tag')->get();

And here is the result :

[
    {
        "bp_chapter_id": 1,
        "bp_chapter_name": "test",
        "tag": [
            {
                "bp_tag_id": 62,
                "bp_hashtag": "test",
                "laravel_through_key": 1
            },
]

and this is what i expected at the result:

[

    {
        "bp_chapter_id": 1,
        "bp_chapter_name": "test",
        "tag": [
            {
                "bp_tag_id": 62,
                "bp_hashtag": "test",
                "laravel_through_key": 1,
                **"content_hashtag_count": 0**
            },

]

how can i get the expected result

>Solution :

To get the content_hashtag_count field in your result, you can use the withCount method in your Eloquent query.

First, you need to define a relation between the Content_hashtag model and the Tag model. You can do this by adding the following method to the Tag model:

public function contentHashtags()
{
    return $this->hasMany(Content_
    hashtag::class, 'bp_tag_id', 
    'bp_tag_id');
}

Then controller looks like that :

   $sections = 
    Chapter::with(['tag' => 
    function($query) {
     $query- 
    >withCount('contentHashtags');
   }])->get();

This will add a content_hashtags_count field to each Tag record in the result, with the count of Content_hashtag records that belong to that Tag.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading