如何在 Laravel 中获取最新帖子?只有最新的

Dan*_*vin 1 laravel

我正在尝试提取最新的任务,然后在删除最新的任务后设置该进度以保持进度更新。

所以,想象一下,我首先解决了 20% 的任务,我添加了一个增加 30% 的进度,然后,我得到了 50%。但是,不知何故,我注意到取得的进展不正确,我必须将其删除,因此,进展必须回到 20%

多一点视觉效果:

20% + 30% = 50%

50% - 30% = 20%

话虽如此,在我的控制器中,我有以下内容:

public function destroy(Request $request, $id)
    {
        $id = Progress::where('id', $id)->first();
        $task = $id->task;
        $id->delete();
        $progress = $task->progresses->(dont know how to get the latest one ???);
        $task->progress = $progress->progress; /* we set the latest progress to be the current one */
        $task->update();
        $task->save();
        return response()->json([
        "code" => 200,
        "message" => "Progress deleted successfully"
        ]);
    }
Run Code Online (Sandbox Code Playgroud)

如何获取最新的将其设置为当前的?

bhu*_*cho 5

latest() 是 Illuminate\Database\Query\Builder 类中定义的函数。

$id = Progress::where('id', $id)->latest()->first(); //to get just the most recent created at.
Run Code Online (Sandbox Code Playgroud)

默认情况下,它采用 created at 列。您可以使用 将其设置为 updated_at ->latest('updated_at')。t 将按降序对您提供的列进行 orderBy 并取最后一个值。