在查询中使用 if 条件计算列

Counting columns with if conidition in query

仅计算 Buy_Rate 大于 Sell_Rate 的列。

我的查询结果不符合预期,这是我错误的结果。

$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();

Inverse:如果sell_rate大于buy_rate那么只计算列数。

laravel eloquent where 不支持比较列。所以你需要使用 raw SQL 来组合两列。你可以做类似的事情,

$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count(); 

希望对您有所帮助!

您可以使用whereColumn

$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
                                 ->whereColumn('buy_rate', '<', 'sell_rate')
                                 ->count();

当您需要查询构建器count()时,也无需调用get()