【问题标题】:Laravel how to write search query with multiple conditions but where records under the same userLaravel如何编写具有多个条件但同一用户下的记录的搜索查询
【发布时间】:2019-11-09 17:01:05
【问题描述】:

我有一个包含库存产品的数据库。另外,我有很多用户,他们的产品属于不同的用户。 所以我需要编写一个具有多个条件的查询,其中搜索需要在不同的表列中,所以它将是一对->orWhere() 语句。但是搜索需要找到属于同一用户的所有产品。但如果我有很多->orWhere() 条件,则查询开始搜索其他查询条件匹配的其他用户下的产品(“title”或“product_number”)。

那么我该如何更改我的代码,我可以在哪里获得所有具有搜索关键字的产品,其中产品在同一用户下?

这是我的代码:

public function searchProduct(Request $search){
    $search_item = $search->search;
    $user = User::where('id', Auth::user()->id)->first();
    $inventory = Inventory::where('client_id', $user->client_id)
                            ->where('product_number', 'like', "%{$search_item}%")
                            ->orWhere('title', 'like', "%{$search_item}%")
                            ->orWhere('other_product_numbers', 'like', "%{$search_item}%")
                            ->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
                            ->paginate(50);

    $cleint_currency = SettingsClientCurrency::where('client_id', $user->client_id)->first();

    $inventory_products = Inventory::where('client_id', $user->client_id)->with('orderInRecord')->get();
    $inventory_total = 0;
    foreach ($inventory_products as $product) {
        $ordersin = $product->orderInRecord;
        foreach ($ordersin as $orderin) {
            $inventory_total += $orderin['price'] * $orderin['units'];

        }
    }

    return view('layouts.inventory.inventory')
            ->with('inventory', $inventory)
            ->with('inventory_total', $inventory_total)
            ->with('cleint_currency', $cleint_currency)
            ->with('user', $user);
}

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    您可以在第二个 where 子句中使用两个带有回调函数的 where 子句。这将得到你想要的结果

    $inventory = Inventory::where('client_id', $user->client_id)
                           ->where(function ($query) use ($search_item) {
                               $query->where('product_number', 'like', "%{$search_item}%")
                                     ->orWhere('title', 'like', "%{$search_item}%")
                                     ->orWhere('other_product_numbers', 'like', "%{$search_item}%");
                           })
                           ->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
                           ->paginate(50);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2013-11-21
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多