Abdu Haseeb
Abdu Haseeb

Reputation: 1

Nested one-to-many relationship Laravel filtering to one record

I have a product model, inventory model, and user_inventory model and the user_inventory model has sale_price. I want to receive the product inventory which has smallest user inventory sale price and also the user_inventory

the output show be like:

products:{
       id
       inventories:{
           id
           product_id
            user_inventories:{
                 id
                 inventory_id
                 sale_price:smallest value
                  }
        }
},.....


Upvotes: 0

Views: 25

Answers (1)

Mehran
Mehran

Reputation: 351

it may help to define a new model relation in inventory model like this:

    public function lowestPrice()
    {
        return $this->hasOne('user_inventory','inventory_id')->orderBy('sale_price');
    }

so it may return lowest sale_price of user_inventory for each inventory

for example:

$product = product::with('inventory.lowestPrice')->first();

Upvotes: 0

Related Questions