[英]Laravel Query builder: Take and limit methods
I dont undertand how these methods work, I'm trying to get last records inserted in my db and for this, I need a query builder so I made y consult with something like this: 我不了解这些方法的工作方式,我试图将最后的记录插入到数据库中,为此,我需要一个查询生成器,因此我向y咨询了以下内容:
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1);
The thing is I'm still getting all records inserted, in these methods take
or limit
I send the paramether of how many i want to get, and my question is. 问题是我仍在插入所有记录,在这些方法中,我
take
或limit
了我要获取的记录的数量,而我的问题是。 Why does this happen?? 为什么会这样?
And no, I dont want to use the first() or get() methods these dont work when you do server side processing in a datattable 不,我不希望使用first()或get()方法在数据表中进行服务器端处理时不起作用
first()
is not return Collection. first()
不返回Collection。 It returns a Model instance. 它返回一个Model实例。 Maybe you are not clear about Collection vs Model instance.
也许您不清楚Collection与Model实例。
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first();
Alternative: 选择:
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->get();
// $costo[0]
take(1)
or limit(1)
just adds limit 1
to the query in builder. take(1)
或limit(1)
只会将limit 1
添加到builder中的查询中。 You need to call get()
to fetch the results and it will return a Collection
and you can get its only element by calling first()
on it. 您需要调用
get()
来获取结果,它将返回一个Collection
并且可以通过在其上调用first()
来获取其唯一元素。
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1)->get()->first();
Or you can replace take(1)->get()->first()
with just first()
或者您可以只用
first()
替换take(1)->get()->first()
first()
$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first()
first()
will add limit 1
and fetch the results and return the only item that's there first()
将添加limit 1
并获取结果并返回那里唯一的项目
Try this 尝试这个
$costo = Costo_promedio::orderBy('created_at','desc')->take(3)->get();
That Will get the last three records from the database assuming that your timestamp is named created_at . 假设您的时间戳名为created_at ,它将从数据库中获取最后三个记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.