duanqiao1947 2019-08-19 08:09
浏览 65
已采纳

为什么我的雄辩查询在以后使用时会被覆盖?

I've encountered a very strange problem and I cannot find the cause of it. I was wondering if someone has encountered the same problem or if its a config problem.

Basically this was my block of code. Very simple stuff.

$productImages = App\ProductImage::where('product_id', $product->id)->orderBy("order", "asc");
$productImages_First = $productImages->first();
$productImages_All = $productImages->get();

If I performed a dump and die on $productImages_All then it would output the following:

Collection {
  #items: array:5
}

This has worked perfectly fine for months. I haven't touched this block of code at all.

However, I've noticed in the last week, that if I dump and die $productImages_All now, it will only return the first image and not all of them.

Collection {
  #items: array:1
}

It seems that the $productImages_First = $productImages->first(); is overwriting it. Is this standard behaviour? It would make complete sense if it was as its calling to the original eloquent query and I should create a separate one to get all of the images. However, what doesn't make sense is that this block of code has worked for months without a change and it has randomly broke.

I can fix this very quickly, I just want to see if I can get more clarity on what may cause this?

  • 写回答

1条回答 默认 最新

  • ds20021205 2019-08-19 08:57
    关注

    That's because when you call first method it modifies the Query/Builder object inside the Eloquent/Builder and sets limit property to 1, so you have to reset it's value before calling get method.

    $productImages = App\ProductImage::where('product_id', $product->id)- 
    >orderBy("order", "asc");
    $productImages_First = (clone $productImages)->first();
    $productImages_All = $productImages->get();
    

    Or you can

    $productImages = App\ProductImage::where('product_id', $product->id)- 
    >orderBy("order", "asc");
    $productImages_First = $productImages->first();
    $productImages->getQuery()->limit=null;
    $productImages_All = $productImages->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算