Jenssen
Jenssen

Reputation: 1871

Laravel eloquent query improvement

Currently I've got this eloquent query:

$products = Product::where('is_send', 1)->with(['articles.stock' => function($query) {
            $query->where('quantity', '>', 0);
        }])->get();

I'm wondering if there is a better way for doing this?

For clarification:

A product hasMany articles

A article hasOne Stock

I need the article_ids where product is_send = 1 and where the articles of that product have quantity > then 0.

Upvotes: 2

Views: 134

Answers (1)

Nikola Gavric
Nikola Gavric

Reputation: 3543

If you are doing this query a lot, then you can create a scope, here is an example:

Product model code

public function scopeltStockQuantity($query, $quantity) {
    return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
        $innerQuery->where('quantity', '>', $quantity);
    }]);
}

Then you can do:

$products = Product::where('is_send', 1)->ltStockQuantity(0)->get();

Or to further separate the code you can do something like this:

Stock model code

public function scopeltQuantity($query, $quantity) {
    return $query->where('quantity', '>', $quantity);
}

Product model code

public function scopeltStockQuantity($query, $quantity) {
    return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
        $innerQuery->ltQuantity($quantity);
    }]);
}

Upvotes: 3

Related Questions