【问题标题】:LARAVEL: I am only getting one item from my table when there are multiple items. How would I get all of them and output them?LARAVEL:当有多个项目时,我只会从我的桌子上拿一个项目。我将如何获得所有这些并输出它们?
【发布时间】:2021-08-27 19:43:33
【问题描述】:

我正在使用会话来创建基本购物车。在会话中有多个ID,范围从1-3。

当我使用 foreach 输出数据时,它只输出表中的第一项。我希望所有相关项目都出现。我该怎么做呢?

这是我的控制器的索引函数:

public function index()
{
    session_start();
    $cartData = implode(',', $_SESSION['cart']);
    $cartProducts = Product::where('id',$cartData)->get();
    return view('basket',['cartProducts'=>$cartProducts ],['cartData' =>$cartData] );
}

这是我在购物车页面上的输出:

  @foreach($cartProducts as $cartProduct)


         <p>{{$cartProduct->name}}</p>
         <p>{{$cartProduct->size}}</p>
         <p>{{$cartProduct->price}}</p>

  @endforeach

出于测试目的,这是我的 $cartData 转储和死亡:

"1,1,3"

最后是实际输出:

Original

small

8

【问题讨论】:

  • 不要使用 $_SESSIONsession_start,你有 Session facade/helper 这样做...... 你没有使用 Laravel,你应该这样做小心你会养成坏习惯......

标签: php database laravel session


【解决方案1】:

你有两个问题:

  1. 您传入的是 ID 字符串而不是数组
  2. where 只查找单个值。

所以查询实际上变成了where id = '1,1,3',它可能只匹配1的id。要修复它,请传入实际数组,然后使用whereIn

Product::whereIn('id', $_SESSION['cart'])->get();

这会将查询更改为where id IN (1,1,3)

【讨论】:

  • 谢谢!已经修复了它:)
【解决方案2】:

您只是在使用 where,这对您想要实现的目标没有帮助。

您应该使用 whereIn(相当于 sql 中的 where())而不内爆(直接使用数组)。

->whereIn('id', $cartData)

这应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2010-12-03
    • 2016-08-26
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多