skip to Main Content

To simplify I have two models, Product and ProductStatus. To record the history of the product status, they are tied with one-to-many relationship with Product being the parent.

Now the question is: How do I query the Product model based on the latest status of the ProductStatus tied to it?

Let’s say I want to query a Product that has a status of "Approved", then the rough idea will probably be something like:

// The status model has a field called status
Product::whereHas("statuses", fn($q) => $q->whereLatest("status", "Approved"))

Note: I need this code in builder instance because I’m assuming I’m going to query a lot of data.

How can I do this?

2

Answers


  1. I would recommend to create a property on the Product model for the current status and create a model observer to monitor changes in this property and create a ProductStatus when necessary. Since you will query a lot of data this will be way more efficient and faster.

    Login or Signup to reply.
  2. Create scope inside the Product Model

    public function scopeStatus(Builder $query, $status)
    {
        return $query->relation()->where('status', $status)->latest();
    }
    

    Use:

    Product::status('Approved')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search