如何将原始查询 MYSQL 转换为 Laravel 框架

我不知道如何在 Laravel 5.8 中使用下面的代码,我已经尝试过,但无法正常工作。


$sql = mysqli_query($db, "SELECT *, SUM(amount) AS SumBudget FROM messages GROUP BY contact_phone ORDER BY SUM(amount) DESC LIMIT 3");


$orderList = 0;

while ($data = mysqli_fetch_assoc($sql))

{

    $orderList++;

    $user = $data['user']; 

    $cost = $data['SumBudget'];

    if ($orderList == 1) {

        printf("%d. %s %d‎฿<br>", $orderList, $user, $cost);

    }

    else if ($orderList == 2)

    {

        printf("%d. %s %d‎฿<br>", $orderList, $user, $cost);

    }

    else 

    {

        printf("%d. %s %d‎฿<br>", $orderList, $user, $cost);

    }

}

我的代码已经试过了。


$data = DB::table('messages')

        ->where('phone_number', $request->phone_number)

        ->select(DB::raw('SUM(amount) as cost'))

        ->groupBy(DB::raw('contact_phone'))

        ->orderBy(DB::raw('SUM(amount)', 'DESC'))

        ->limit(3)

        ->get();

谁能帮帮我,谢谢。


MYYA
浏览 191回答 1
1回答

慕森王

我认为它可以帮助你:DB::table('messages') &nbsp;&nbsp;&nbsp;&nbsp;->select('column_name',&nbsp;/*&nbsp;...&nbsp;*/,&nbsp;DB::raw('SUM(amount)&nbsp;AS&nbsp;cost')) &nbsp;&nbsp;&nbsp;&nbsp;->where('phone_number',&nbsp;$request->phone_number)&nbsp;//&nbsp;if&nbsp;you&nbsp;want&nbsp;to&nbsp;filter &nbsp;&nbsp;&nbsp;&nbsp;->groupBy('contact_phone') &nbsp;&nbsp;&nbsp;&nbsp;->orderBy('cost',&nbsp;'DESC') &nbsp;&nbsp;&nbsp;&nbsp;->take(3) &nbsp;&nbsp;&nbsp;&nbsp;->get()
打开App,查看更多内容
随时随地看视频慕课网APP