许多答案和一些我不太同意的地方。所以我再用我的cmets总结一下。
如果您刚刚创建了一个新对象。
默认情况下,当你创建一个新对象时,Laravel 会返回这个新对象。
$lastCreatedModel = $model->create($dataArray);
dd($lastCreatedModel); // will output the new output
echo $lastCreatedModel->key; // will output the value from the last created Object
还有一种方法是在没有条件的情况下将all() 与 (last()and first()) 方法结合起来。
非常糟糕!不要那样做!
Model::get()->last();` // the most recent entry
Model::all()->last();` // the most recent entry
Model::get()->first();` // the oldest entry
Model::all()->first();` // the oldest entry
这基本上是错误的方法!你get()all() 记录,在某些情况下可能是 200,000 或更多,然后只挑出一行。不好!想象一下,您的网站正在从 Facebook 获得流量,然后是这样的查询。在一个月内,这可能意味着像巴黎这样的城市一年的二氧化碳排放量。因为服务器必须不必要地努力工作。所以忘记这种方法,如果你在你的代码中找到它,替换它/重写它。也许你不会注意到 100 个数据集,但如果有 1000 个或更多数据集,它就会很明显。
非常好:
Model::orderBy('id', 'desc')->last(); // the most recent record
Model::latest('id')->first(); // the most recent record
Model::latest('id')->limit(1)->get(); // the most recent record
Model::orderBy('id', 'desc')->limit(1)->get(); // the most recent entry
Model::orderBy('id', 'desc')->first(); // the most recent entry
Model::orderBy('id', 'asc')->first(); // the oldest entry
Model::orderBy('id', 'asc')->limit(1)->get(); // the oldest entry
Model::orderBy('id', 'asc')->first(); // the oldest entry
如果在此上下文中使用 orderBy,则应始终将主键用作基础,而不是 create_at。