1 year ago

How to get only one row of one to many with condition?

Posted 1 year ago by aarad

I have many product that each product can has many inventory in inventories table.

I want to sort each product.inventories by inventory.id that inventory.count > 0 and get first.

Then i want to sort products by inventory.price.

$products = Product::with(['inventories' => function($query){
     $query->where('count', '>', 0)->orderBy('id')->first();  // this is return only one inventory for last product
$products->orderBy('inventories.price')->get();  // this give me an error

Relation on Product model:

public function inventories()
    return $this->hasMany(Inventory::class)->orderBy('expiration_date', 'desc');

How can i do it.

Sorry for my bad english.

Please sign in or create an account to participate in this conversation.