【发布时间】:2021-05-06 00:45:50
【问题描述】:
您好,我正在尝试从我的数据库中获取投票计数结果,但不确定最佳方法。
主题模型
protected $fillable = [
'division_id',
'date',
'title',
'description',
'aye_count',
'noe_count'
];
public function votes()
{
return $this->hasMany(Vote::class, 'topic_id', 'division_id');
}
投票模式
protected $fillable = [
'topic_id',
'user_id',
'user_aye_count',
'user_noe_count'
];
function topic() {
return $this->belongsTo(Topic::class, 'topic_id', 'division_id');
}
我的控制器是这样的
public function filterTopicsByTitle(Request $request)
{
$division_id = $request->get('filterTopicsByTitle');
$topicResults = Topic::with(['votes'])->where('division_id', $division_id)->first();
dd($topicResults->votes);
return view('dashboard', compact('topicResults'));
}
转储输出以下内容
Illuminate\Database\Eloquent\Collection {#1259 ▼
#items: array:2 [▼
0 => App\Models\Vote {#1263 ▼
+timestamps: false
#fillable: array:4 [▶]
#connection: "mysql"
#table: "votes"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▼
"id" => 1
"user_id" => 2
"topic_id" => 965
"user_aye_count" => 1
"user_noe_count" => null
]
#original: array:5 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => App\Models\Vote {#1265 ▼
+timestamps: false
#fillable: array:4 [▶]
#connection: "mysql"
#table: "votes"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▼
"id" => 5
"user_id" => 1
"topic_id" => 965
"user_aye_count" => null
"user_noe_count" => 1
]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
我基本上需要用总数创建 2 个变量 $userAyeCount 和 $userNoeCount。我能想到的唯一方法是使用 foreach 循环获取行 user_aye_count 或 user_noe_count 并递增变量。
这似乎不是正确的方法,当有大量或行时,我猜它会慢得多。任何帮助将不胜感激。
【问题讨论】:
-
您需要对这些“求和”吗?因为 Eloquent 有一种基于关系计数或字段等进行聚合的方法
标签: laravel eloquent laravel-8