【问题标题】:Running where() more more than one time多次运行 where()
【发布时间】:2020-07-24 06:47:07
【问题描述】:

问题:如何对 $cart 中的所有行运行 where 查询,而不是仅对 $cart[0]、[1] 或 [2] 进行查询。

我正在尝试在 Laravel 中手动编写购物车代码。由于我是新手,所以我被困在一个点上。请看下面的代码:

public function showCart()
{
    $user = Auth::user();
    $cart = Cart::where('user_id', $user->id)->get();
    $product = Products::where('id', $cart[0]->product_id)->get();
    return view('showCart')
           ->with('cart', $cart)
           ->with('user', $user)
           ->with('product', $product);
}

这是我显示用户购物车的功能。在这里,我试图显示用户在他的购物车中拥有的所有产品,并发送一个包含产品详细信息的变量。

但是,当我尝试将用户购物车中的所有产品作为 $product 数组发送时,我只获得了第一个产品。那是因为 $cart 中返回的行不止一个,但是我无法编写查询来获取该行中的所有产品:

$product = Products::where('id', $cart[0]->product_id)->get();

。 . .因为,很明显,我正在编写一个查询来匹配 $cart 中返回的第一行。

提前致谢。

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-4


    【解决方案1】:

    您可以使用whereIndata_get 辅助函数:

    $product = Products::whereIn('id', data_get($cart, '*.product_id'))->get();
    

    data_get 适用于数组和对象。或者,您可以将Arr::get 仅用于数组。

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 2018-06-07
      • 2013-01-15
      • 2020-03-29
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      相关资源
      最近更新 更多