orWhere vs Where Laravel 5.1 [英] orWhere vs Where Laravel 5.1

查看:59
本文介绍了orWhere vs Where Laravel 5.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$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;

除了->where('amount', '<', 100)->where('amount', '>', 10)之外,其他所有功能都可以正常工作.

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

它不排除任何一个,并且显示我设置的数字之上和之下的金额.如果我删除orWhere(),它将正常工作.

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.

我正确使用orWhere()where()吗?

推荐答案

问题是您在合并OR和AND时没有正确分组.考虑以下条件:

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

因此,要使其正常工作,您需要对条件进行正确分组.您可以通过将闭包传递给where()orWhere()方法来对条件进行分组.我猜想您要将$text条件分组在一起,因此您的代码应如下所示:

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;

这篇关于orWhere vs Where Laravel 5.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆