简体   繁体   中英

Laravel Eloquent Query Where nested relationship

I am new to laravel and i am trying to write a query whereby the selected stock->OrderProduct->product_id is passed to get the relevant result. The query looks like this :

$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;

This doesnt work as it is bad practise and i rewrote the query like below, which brings me wrong results.

$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(); 

Any advise on eloquent methods to use when i want to pass a condition based on relationships in a query will be highly appreciated. I am using lavel 5.8

I used 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM