Reputation: 9220
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
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!
Upvotes: 1
Views: 749
Reputation: 25926
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();
Upvotes: 0
Reputation: 13259
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;
}
Upvotes: 0