2
votes

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.

1
is this working?? add your table column info with the questionsSohel0415
If you could filter articles by something it would be good but if not then it's either this query or a 3 table join. A 3 table join might be slightly quicker. However the question is, does stock really need to be a separate entity from article since it appears to be 1 to 1apokryfos
I agree with @apokryfos, you are best off with the query you presented, all you can do is optimize it by creating a scope, this applies if you are using or going to be using it a lotNikola Gavric

1 Answers

3
votes

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);
    }]);
}