我正在嘗試使用 Eloquent 做一個簡單的查詢。我的test_registrants表看起來像這樣
我想與所有的價值添加新列user_id與payment_status = 1
這是我的查詢使用 whereColumn
TestRegistrant::select(['test_registrants.*'])
->where('payment_status', 1)
->addSelect([
'attempt' => TestRegistrant::select(DB::raw('count(*) as attempt'))
->whereColumn('test_registrants.user_id', 'user_id')
->where(function ($query) {
$query->where('payment_status', 1);
})
]);
但我得到的一切user_id,而不是

我想要實作的是這個

那么我在這里做錯了什么?謝謝你
uj5u.com熱心網友回復:
您的查詢回傳的原因是3,它只是計算所有具有payment_status = 1. 該whereColumn()作業不正常,因為它沒有反映正確的列。
當您alias為表user_id上的列定義 an 時test_registrants,它應該可以作業。例如,您可以將其命名為:outer_user_id。我已相應地更新了您的示例:
TestRegistrant::select(['test_registrants.payment_status', 'test_registrants.user_id as outer_user_id'])
->where('payment_status', 1)
->addSelect([
'attempt' => TestRegistrant::selectRaw('count(*) as attempt')
->whereColumn('test_registrants.user_id', 'outer_user_id')
->where(function ($query) {
$query->where('payment_status', 1);
})
])
->get();
或者,您也可以查看grouping結果,以便您可以計算特定組中的所有行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371276.html
