我有以下代码:
$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)。
->where('amount', '<', 100)
->where('amount', '>', 10)
它不排除任何一个,并且显示的金额高于和低于我设置的数字。如果我删除orWhere()它工作正常。
orWhere()
我使用的orWhere()和where()正确的?
where()
问题是您没有将OR和AND组合在一起,而是对其进行了正确分组。考虑以下条件:
$bool1 = false && false || true; // =true $bool2 = false && (false || true); // =false
因此,要使其正常工作,您需要对条件进行正确分组。您可以通过将闭包传递给where()或orWhere()方法来对条件进行分组。我猜您想将$text条件分组在一起,因此您的代码如下所示:
$text
$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;