0

I'm using Laravel 4.2 Query Scopes but encountered a problem.

My Model:

class SomeModel extends Eloquent {
    public function scopeS1($query) {
        return $query->where('field1', '=', 'S1');
    }
    public function scopeS2($query) {
        return $query->where('field2', '=', 'S2');
    }
}

Now when I do SomeModel::s1()->s2()->get(); it returns all results and doesn't filter by S1 AND S2. Note also that I have no problem when I do

SomeModel::where('field1', '=', 'S1')->where('field2', '=', 'S2')->get()

So why is query scoping and doing anything here??

2
  • What does SomeModel::s1()->s2()->toSql() return? Commented Apr 18, 2015 at 13:43
  • It happens that the returned result is different depending on the order of s1() and s2() usage. My scope functions are a bit more complex than what I have in question, so won't bother entering the toSql() here but what should be noted is that I don't see any paranthese around operators in the SQL output, which I think explains the issue. So how can I do, for example (field1 = 'S1' OR field1 = 'any') AND field2 = 'S2' instead of field1 = 'S1' OR field1 = 'any' AND field2 = 'S2' using scopes? Commented Apr 18, 2015 at 14:00

1 Answer 1

3

Since your real scopes contain OR conditions you should use a nested where to make sure they get interpreted correctly. Laravel will wrap parentheses around.

public function scopeS1($query) {
    return $query->where(function($q){
        $q->where('field1', '=', 'S1')
          ->orWhere('foo', '=', 'bar');
    });
}

// and the same for scopeS2...
Sign up to request clarification or add additional context in comments.

2 Comments

lovely gobely! I never used nested wheres in Laravel before. Thank you!
Thank you so much. I had an issue that queries to the current model would fail because it would fetch ALL possible relationships instead of the relationships belonging to relations. doing a $that = $this;$query->where(function($query) use ($that){}); I was able to use the objects properly. You saved me from a 6 hour horror in which I could not figure out why it would fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.