Alberto
Alberto

Reputation: 173

Withcount() with relationship

I have this query. I want to bring all the posts, with their direct relations and the comment count, but I also want to add the count of a relation with survey.

$posts = Post::with('survey.surveyOptions', 'image', 'categories')
            ->withCount('comments')
            ->paginate(9);

I want to bring the count of this relationship:

class Survey extends Model
{
    use HasFactory;
    protected $guarded = ['id'];
    public function totalSurveys()
    {
        return $this->hasMany(Option_value::class);
    }
}

The post model has this relationship with survey:

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

How can I get the totalSurveys count?

Upvotes: 0

Views: 431

Answers (1)

Robbin Benard
Robbin Benard

Reputation: 1652

By passing an array to with() you can add constraints to the query. https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

$posts = Post::with([
    'survey' => function ($query) {
        $query->withCount('totalSurveys');
    },
    'survey.surveyOptions', 
    'image', 
    'categories'
  ])
  ->withCount('comments')
  ->paginate(9);

Upvotes: 2

Related Questions