【问题标题】:Laravel Eloquent Query using Where, With, Where and orWhere conditionLaravel Eloquent Query 使用 Where、With、Where 和 orWhere 条件
【发布时间】:2021-07-12 17:32:15
【问题描述】:

我正在尝试进行 Laravel Eloquent 查询,它将通过订单号和产品名称找到我的订单。 我有 3 个表订单、order_details 和产品。

订单表

id    |   user_id    |    order_id    |    order_cart_id
---------------------------------------------------------
1     |      1       |  123-456-7890  |          1
2     |      1       |  789-456-3210  |          2

order_details 表

id    |   order_id   |    cart_id     |        p_id 
---------------------------------------------------------
1     |      1       |        1       |          22
2     |      1       |        1       |          42
3     |      1       |        1       |          2
4     |      1       |        1       |          32
5     |      1       |        1       |          423
6     |      2       |        2       |          432

产品表

id    |    p_name
--------------------
1     |      ABC       
2     |      CAD       
42    |      PRO       
22    |      XYZ
32    |      IND    
423   |      MP
432   |      ETC

订单模型

public function order_cart_products()
{
    return $this->hasManyThrough(\App\Models\Products\Product::class,
        \App\Models\Orders\OrderDetail::class,
        'cart_id',
        'id',
        'cart_id','p_id');
}

订单控制器

$orders = Order::where('user_id', auth()->user()->id)
    ->where('order_id', 'LIKE', '%'.$search.'%')
    ->with('order_cart_products', function ($query) use ($search) {
        $query->orWhere('p_name', 'LIKE', '%'.$search.'%');
    })
    ->get()->toArray();

我要做的是搜索order_id(123-456-7890),如果我通过p_name(ABC) 搜索,我需要获取其中包含产品的所有详细信息。我需要获取所有列出 ABC 的订单。但是我不明白我哪里出错了没有得到想要的输出。

【问题讨论】:

  • with 不会影响查询本身。它使用辅助查询获取关系并将它们加载到各个模型中,因此如果您稍后尝试使用这些关系,它将使用加载的关系(可以过滤),而不是为该单个模型运行查询。跨度>

标签: laravel eloquent laravel-8


【解决方案1】:

试试下面的方法:

$orders = Order::with('order_cart_products')
    ->where('user_id',auth()->user()->id)
    ->where(function ($query) use ($search) {
        $query->where('order_id', 'LIKE', '%'.$search.'%')
            ->orWhereHas('order_cart_products', function ($query) use ($search) {
                $query->where('p_name', 'LIKE', '%'.$search.'%')
            })
    })
    ->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2020-07-09
    • 2013-06-04
    • 2020-06-27
    相关资源
    最近更新 更多