-
Is it possible to access a models scopes within a subquery? Let's say we have an Order model with a scope method named paid(). class Order extends Model
{
public function scopePaid($query)
{
$query->where('payment_status', '=', 'paid')
->where('order_status', '!=', self::STATUS_CANCELED)
->where('order_status', '!=', self::STATUS_REVOKED);
}
} Within this same model, let's assume we want to add a scope which filters orders by unique emails by running a subquery on the same model. public function scopeOnlyWithNewCustomers($query)
{
$query->whereIn('email', function($subQuery)
{
// This will not work, because the QueryBuilder which is injected (($subQuery), knows NOTHING of the Order::model
// so none of the models scopes are available to me.
$subQuery->select('email')
->paid()
->groupBy('email')
->havingRaw('COUNT(email) = 1');
});
} If I want the above to work, I would actually have to write the following: public function scopeOnlyWithNewCustomers($query)
{
$query->paid()->whereIn('email', function($subQuery) {
$subQuery->select('email')->from('orders')
->where('payment_status', '=', 'paid')
->where('order_status', '!=', self::STATUS_CANCELED)
->where('order_status', '!=', self::STATUS_REVOKED)
->groupBy('email')
->havingRaw('COUNT(email) = 1');
});
} Obviously this is a very simplified example, the question basically boils down to: How can I have Laravel/Winter inject a QueryBuilder for the model, instead of a base QueryBuilder. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@datune I might be wrong, but I'm pretty confident that subqueries are intentionally limited to not include scopes (besides, perhaps, global scopes) because it becomes difficult for the query builder to work out which bindings, tables, columns, etc. need to be fed to the subquery and which ones need to be fed to the main query, and scopes would certainly complicate that process even further. I would say that yes, your longer scope which contains the full query in the subquery would have to be used in this instance. |
Beta Was this translation helpful? Give feedback.
-
I found a very clever solution for this problem: https://hashnode.com/post/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable-ciylr4k0r001os453wuvd4t8w |
Beta Was this translation helpful? Give feedback.
I found a very clever solution for this problem: https://hashnode.com/post/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable-ciylr4k0r001os453wuvd4t8w