Home > Net >  How to get products that the sellers have reduced their prices in laravel
How to get products that the sellers have reduced their prices in laravel

Time:01-22

I have a table called products that each time a user updates their product, a new row is saved in another table called product_price_history.

My Tables :

products :

id  (primary key)
name  (varchar)
price  (decimal)

product_price_history :

id  (primary key)
product_id  (fk to products)
price  (decimal)
created_at (dateTime)

My Models :

  • Product

  • ProductPriceHistory

I have written the relationship of the child table inside the product model as follows

class Product extends Model {


  public function history()
  {
     return $this->hasMany(ProductPriceHistory::class, 'product_id', 'id');
  }


}

How do I write a query in Laravel that displays a list of products with declining prices? In other words, show the list of products whose prices have recently decreased.

   $result = Product::whereHas('history' , function($query){

   // I do not know what to write here ...


   })->get();

CodePudding user response:

The query you created is correct, just add the descending order filter

the query will be like this:

   $result = Product::whereHas('history' , function($query){
       $query->orderBy('price', 'DESC');
   })->get();

CodePudding user response:

use in Model

protected $with = ['history'];
  •  Tags:  
  • Related