【问题标题】:Laravel - Query builder with pivot table, return where all inLaravel - 带有数据透视表的查询构建器,返回所有位置
【发布时间】:2017-12-05 14:41:58
【问题描述】:

我有表客户、产品和customer_products。 在customer_products 中有idcustomer_idproduct_id 列。 在搜索表单中,我有“products”输入字段,并且可以添加多个产品进行搜索。 因此,在这种情况下,$request->products 是数组,我想在查询生成器中传递该数组,以返回所有从$request->products 数组中至少购买了所有产品的客户。 如果每个客户只有一种产品,我会使用 whereIn 方法,但是当客户订购了多种产品时,我不知道如何解决这个问题。 我尝试了 foreach 但我没有得到想要的结果。

【问题讨论】:

    标签: laravel-5


    【解决方案1】:

    我终于找到了解决办法。如果有人有同样的问题,这是给我正确结果的解决方案, whereHas 方法是我需要的:

    $customesrs = Customers::with('products');
    if($request->has('products'))
    {
      foreach($request->products as $product)
      {
       $customers->whereHas('products', function($query) use ($product) {
         $query->where('product_id', $product);
       });
      }
    }
    $customers->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2018-03-06
      • 2019-11-15
      • 2020-09-07
      • 1970-01-01
      • 2018-11-11
      相关资源
      最近更新 更多