我正在为组织开发专业的Web应用程序,但是我需要使用字段来统计每个部门中的用户总数。这是我的四个表用户
user_fields
sectors表属性(id(PK),名称,子弹,desc
字段表属性(id(PK),名称,sector_id(FK),slug,desc
user_fields表属性(id(pk),user_id(FK),字段(FK)
用户表属性(id(pk),全名,地址
这是我有关系的模型
class Sector extends Model
{
public function field()
{
return $this->hasMany(Field::class);
}
}
class Field extends Model
{
public function sector()
{
return $this->belongsTo(Sector::class)->withDefault();
}
public function user_field()
{
return $this->hasMany(UserField::class);
}
}
class UserField extends Model
{
public function field ()
{
return $this->belongsTo(Field::class)->withDefault();
}
public function user()
{
return $this->belongsTo(User::class)->withDefault();
}
}
class User extends Model
{
public function user_field()
{
return $this->hasMany(UserField::class);
}
}
我已经在字段级别尝试过,成功的是我的代码
$fields = Field::withCount('user_field')->inRandomOrder()->get();
输出
fields
1. doctors(3)
2. nursing(4)
3. teachers (4)
如果要使用SQL查询,我希望在扇区级别上实现
Select count(s.name) from sectors s,fields f,member_fields mf where s.id = f.sector_id and f.id = mf.field_id group by s.name
它可以工作,但我想将其转换为Laravel
我想要这个输出
Sector
Education (3)
Health (50)
Agriculture (8)