我有客户,其用户,其中包含带有多对多表格的调查。所以user_surveys。
我想知道如何深入计算某些关系。我想计算用户对该客户的所有调查
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();
}
这是我的员工方法,它是用户的子集
public function employees()
{
return $this->users()->whereHas('roles', function ($q) {
$q->where('name', 'employee');
});
}
这是用户模型
命名空间App \ Models;
使用App \ LoginToken; 使用Illuminate \ Notifications \ Notifiable; 使用Illuminate \ Foundation \ Auth \ User作为Authenticatable; 使用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);
}
}
可能会迟到,我可能会感到困惑和/或愚蠢。 期待您的回复!
答案 0 :(得分:0)
另一种方法是
$user = App\User::find(1);
return $user->surveys()->count();
或尝试
$users = App\User::withCount('surveys')->get();
foreach($users as $user) {
$user->surveys_count;
}
答案 1 :(得分:0)
试试这个:
return $this->employees()->withCount('surveys')->get();
答案 2 :(得分:0)
在这种情况下没有本机关系。
我创建了HasManyThrough
关系,并支持BelongsToMany
:Repository on GitHub
安装后,您可以像这样使用它:
class Client extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function surveys() {
return $this->hasManyDeep(Survey::class, [User::class, 'user_surveys']);
}
}
$count = $client->surveys()->count();