1

I'm trying to fetch relational count which is in many-to-many relation in my Laravel 7.30 application. I've a many-to-many relational table named project_associate_brand which has project_id, product_group_id, product_subgroup_id and brand_id, so my table looks like:

project_id     product_group_id    product_subgroup_id    brand_id
   1                    1                     1               1
   1                    1                     1               2
   1                    2                     3               1
   

In the above table I want to fetch Groups with projects count so in my model Group I defined the relation as below:

public function projects()
{
    return $this->belongsToMany(Project::class, 'project_associate_brand', 'product_group_id', 'project_id');
}

and similarly I've relation defined in Project model:

public function groups()
{
    return $this->belongsToMany(Group::class, 'project_associate_brand', 'project_id', 'product_group_id');
}

By defining the above relation I'm unable to get unique project counts since duplicate rows are present due to the table structure, so now I followed this link and I added distinct in the relationship

public function projects()
{
    return $this->belongsToMany(Project::class, 'project_associate_brand', 'product_group_id', 'project_id')->distinct();
}

Same in the Project model:

public function groups()
{
    return $this->belongsToMany(Group::class, 'project_associate_brand', 'project_id', 'product_group_id')->distinct();
}

Also tried other options but it is not working through, maybe some elegant solution might be available which I'm unaware

Help me out, Thanks

Nitish Kumar
  • 6,054
  • 21
  • 82
  • 148
mayuri
  • 31
  • 1

0 Answers0