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
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 aProductStatus
when necessary. Since you will query a lot of data this will be way more efficient and faster.Create scope inside the Product Model
Use: