【发布时间】:2020-11-01 10:18:46
【问题描述】:
我在 laravel 上工作时遇到了麻烦,无法统计有多少用户赞助了这张名为 users 的表格,数据如下所示。
|--------------|---------------- |-------------|
| id | first_name | sponsor_id |
|--------------|------------------|-------------|
| 59 | kaqefizew | NULL |
|--------------|------------------|-------------|
| 68 | fucifaxe | 59 |
|--------------|------------------|-------------|
| 81 | fepetora | 59 |
|--------------|------------------|-------------|
| 82 | kixys | 81 |
|--------------|------------------|-------------|
并且需要如下输出
|--------------|---------------- |------------------|
| id | first_name | sponsored_count |
|--------------|------------------|------------------|
| 59 | kaqefizew | 2 |
|--------------|------------------|------------------|
| 68 | fucifaxe | 0 |
|--------------|------------------|------------------|
| 81 | fepetora | 1 |
|--------------|------------------|------------------|
| 82 | kixys | 0 |
|--------------|------------------|------------------|
我尝试使用计数子句
SELECT id, first_name, COUNT(sponsor_id) as sponsored_count FROM `users` GROUP BY id
但我得到如下错误输出
|--------------|---------------- |------------------|
| id | first_name | sponsored_count |
|--------------|------------------|------------------|
| 59 | kaqefizew | 0 |
|--------------|------------------|------------------|
| 68 | fucifaxe | 1 |
|--------------|------------------|------------------|
| 81 | fepetora | 1 |
|--------------|------------------|------------------|
| 82 | kixys | 1 |
|--------------|------------------|------------------|
关系
class User extends Authenticatable implements JWTSubject
{
public function sponsor( ){
return $this->belongsTo( User::class, 'sponsor_id', 'id' );
}
}
请帮我解决这个问题。
谢谢
【问题讨论】:
-
你能分享更多关于你的模特和他们的关系的信息吗?
标签: mysql sql laravel eloquent count