1
votes

I have Clients, which have Users, which have Surveys with a many-to-many table. So user_surveys.

I'm wondering how I can count some relations deep. I would like to the count of all surveys the users have for that client

What I've tried

Client.php

public function countSurveys()
{
    $employees = $this->employees;

    // this returns Property [surveys] does not exist on this collection instance.
    return $employees->surveys->count();

    // Method whereHas does not exist
    return $employees->whereHas('surveys')->count();
}

This my employees method, which is a subset of Users

public function employees()
{
    return $this->users()->whereHas('roles', function ($q) {
        $q->where('name', 'employee');
    });
}

And this is the User model

namespace App\Models;

use App\LoginToken; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{

public function surveys()
{
    return $this->belongsToMany(Survey::class, 'user_surveys', 'user_id', 'survey_id')
        ->withPivot('completed_on', 'status')
        ->withTimestamps();
}

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

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

}

It might be late, I might be confused and/or stupid. Looking forward to your responses!

3
Can you dd($employees) and tell us what object is that?Marco Aurélio Deleu
Can you post your employees() function and Employee ModelParas
@Paras Thanks for your answer, I added them both.Miguel Stevens

3 Answers

0
votes

Another approach would be

$user = App\User::find(1);
return $user->surveys()->count();

Or try

$users = App\User::withCount('surveys')->get();
foreach($users as $user) {
    $user->surveys_count;
}
0
votes

Try this:

return $this->employees()->withCount('surveys')->get();
0
votes

There is no native relationship for this case.

I created a HasManyThrough relationship with support for BelongsToMany: Repository on GitHub

After the installation, you can use it like this:

class Client extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function surveys() {
        return $this->hasManyDeep(Survey::class, [User::class, 'user_surveys']);
    }
}

$count = $client->surveys()->count();