Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

php - orWhere vs Where Laravel 5.1

I have the following code:

$results = DB::table('pack')
            ->Join('users as u1', 'u1.id', '=', 'pack.userid')
            ->Join('skills as s1', 's1.packid', '=', 'pack.packid')
            ->where('u_status', '=', "0")
            ->where('pack.amount', '<', 100)
            ->where('pack.amount', '>', 10)                 
            ->where('pack_status', '=', "2")
            ->where('pack.title', 'LIKE', "%$text%")
            ->orWhere('pack.description', 'LIKE', "%$text%")
            ->orWhere('pack.skills', 'LIKE', "%$text%")
            ->orWhere('s1.name', 'LIKE', "%$text%")
            ->orderBy('packid', 'desc')
            ->orderBy('featured', 'desc')
            ->groupBy('packid')
            ->take(40)
            ->get();
return $results;

Everything is working except ->where('amount', '<', 100) and ->where('amount', '>', 10).

It does not exclude either of those, and shows amounts above and below the numbers I set. If I remove the orWhere() it works fine.

Am I using orWhere() and where() correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that you've combined ORs and ANDs without grouping them properly. Think about the following conditions:

$bool1 = false && false || true; // =true
$bool2 = false && (false || true); // =false

So, to get this to work properly, you need to group your conditions properly. You can group conditions by passing a closure to the where() or orWhere() methods. I'm guessing you want to group the $text conditions together, so your code would look like:

$results = DB::table('pack')
    ->join('users as u1', 'u1.id', '=', 'pack.userid')
    ->join('skills as s1', 's1.packid', '=', 'pack.packid')
    ->where('u_status', '=', "0")
    ->where('pack.amount', '<', 100)
    ->where('pack.amount', '>', 10)                 
    ->where('pack_status', '=', "2")
    ->where(function($query) use ($text) {
        $query->where('pack.title', 'LIKE', "%$text%")
            ->orWhere('pack.description', 'LIKE', "%$text%")
            ->orWhere('pack.skills', 'LIKE', "%$text%")
            ->orWhere('s1.name', 'LIKE', "%$text%");
    })
    ->orderBy('packid', 'desc')
    ->orderBy('featured', 'desc')
    ->groupBy('packid')
    ->take(40)
    ->get();

return $results;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...