【问题标题】:Laravel Eloquent Query Where nested relationshipLaravel Eloquent 查询嵌套关系
【发布时间】:2020-11-20 12:22:12
【问题描述】:

我是 laravel 的新手,我正在尝试编写一个查询,通过该查询传递选定的 stock->OrderProduct->product_id 以获得相关结果。查询如下所示:

$stock = Stock::where('orderProductid.product_id', $pharmacyEvent->prescription->product_id)
                ->whereHas('orderProduct.product.prices')
                ->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
                    $query->where('scheme_id', $paymentMode->scheme_id);
                }])->first();

            $price = $stock->orderProduct->product->price;

这不起作用,因为这是不好的做法,我重写了如下查询,这给我带来了错误的结果。

$stock = Stock::whereHas('orderProduct.product.prices')
        ->with([
            'orderProduct.product' => function ($query) {
                $query->where('id', $pharmacyEvent->prescription->product_id);
            },
            'orderProduct.product.price' => function($query) {
                $query->where('scheme_id', $paymentMode->scheme_id);
            }
        ])->first(); 

当我想根据查询中的关系传递条件时,任何关于使用雄辩方法的建议都将受到高度赞赏。我正在使用 lavel 5.8

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我用 whereHas :

    $stock = Stock::whereHas('orderProduct.product', function($query) use ($pharmacyEvent) {
                        $query->where('id', $pharmacyEvent->prescription->product_id);
                    })    
                   // ->whereHas('orderProduct.product.prices')
                    ->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
                        $query->where('scheme_id', $paymentMode->scheme_id);
                    }])->first();
    
                $price = $stock->orderProduct->product->price;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2020-03-19
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多