Laravel Query构建器:获取和限制方法

问题描述 投票:0回答:3

我不明白这些方法是如何工作的,我正在尝试将最后的记录插入到我的数据库中,为此,我需要一个查询构建器,所以我咨询了这样的事情:

 $costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1);

事情是我仍然插入所有记录,在这些方法takelimit我发送了多少我想得到的参数,我的问题是。为什么会这样?

不,我不想使用first()或get()方法,当你在datattable中进行服务器端处理时这些方法不起作用

php laravel laravel-5 laravel-query-builder
3个回答
1
投票

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]

1
投票

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并获取结果并返回唯一的项目


0
投票

试试这个

$costo = Costo_promedio::orderBy('created_at','desc')->take(3)->get();

这将从数据库中获取最后三条记录,假设您的时间戳名为created_at。

© www.soinside.com 2019 - 2024. All rights reserved.