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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助