我不明白这些方法是如何工作的,我正在尝试将最后的记录插入到我的数据库中,为此,我需要一个查询构建器,所以我咨询了这样的事情:
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1);
事情是我仍然插入所有记录,在这些方法take
或limit
我发送了多少我想得到的参数,我的问题是。为什么会这样?
不,我不想使用first()或get()方法,当你在datattable中进行服务器端处理时这些方法不起作用
first()
不归还收藏品。它返回一个Model实例。也许你不清楚Collection vs Model实例。
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first();
替代方案:
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->get();
// $costo[0]
take(1)
或limit(1)
只是将limit 1
添加到构建器中的查询中。你需要调用get()
来获取结果,它将返回一个Collection
,你可以通过调用first()
获得它唯一的元素。
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1)->get()->first();
或者你可以用take(1)->get()->first()
替换first()
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first()
first()
将添加limit 1
并获取结果并返回唯一的项目
试试这个
$costo = Costo_promedio::orderBy('created_at','desc')->take(3)->get();
这将从数据库中获取最后三条记录,假设您的时间戳名为created_at。