You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel最近浏览商品列表返回空数组问题求助

问题分析与解决方案

核心问题1:Session键名拼写错误

代码中判断Session时使用了错误的键名seasion_id(少了一个s),导致每次访问商品详情页都会生成新的session_id,无法关联到之前浏览记录的session标识,最终查询不到历史浏览数据。

核心问题2:查询逻辑可优化

原代码中先get()再take(4)会查询所有符合条件的数据再截取,效率较低;同时重复插入的判断逻辑可以简化。


修复后的完整代码

public function ProductDetails($id){   //display the product page detail
    $product = Product::findOrFail($id);
    $multiImg = MultiImg::where('product_id',$id)->get();

    // Set Session for Recently Viewed Products - 修复键名拼写错误
    if(empty(Session::get('session_id'))){
        $session_id = md5(uniqid(rand(), true));
    } else {
        $session_id = Session::get('session_id');
    }
    Session::put('session_id',$session_id);

    // Insert product in table if not already exists - 用firstOrCreate简化逻辑
    DB::table('recently_viewed_products')->firstOrCreate(
        ['product_id' => $id, 'session_id' => $session_id]
    );

    // Get Recently Viewed Products Ids - 优化查询顺序,先take再pluck
    $recentProductIds = DB::table('recently_viewed_products')
        ->select('product_id')
        ->where('product_id','!=',$id)
        ->where('session_id',$session_id)
        ->inRandomOrder()
        ->take(4)
        ->pluck('product_id');
    
    // Get Recently Viewed Products
    $recentlyViewedProducts = Product::whereIn('id',$recentProductIds)->get()->toArray();

    return view('frontend.product.product_details',compact('product','multiImg','recentlyViewedProducts','recentProductIds'));
} // end method

额外验证步骤

  1. 访问多个商品详情页后,查看recently_viewed_products表,确认同一session_id下有多个不同的product_id记录。
  2. 在代码中添加dd($session_id, $recentProductIds),确认session_id在多次访问中保持一致,且$recentProductIds能获取到非空的ID集合。
  3. 检查Product模型的主键是否为id,若主键是product_id,则需将whereIn('id',$recentProductIds)改为whereIn('product_id',$recentProductIds)。

内容的提问来源于stack exchange,提问作者Dev12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:15:27