You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Eloquent中编写AND条件?将orWhere替换为等效AND逻辑

Solution: Replace orWhere with where for AND Logic

Got it, let's adjust your query to use AND logic instead of OR. The fix is straightforward since Laravel's where method uses AND as the default logical operator between conditions.

Original Code (OR Logic)

$jobs = Jobs::where('location','like', '%' . $request->location .'%')
            ->orWhere('category', 'like', '%' . $request->category . '%')
            ->get();

Modified Code (AND Logic)

Simply swap out orWhere with where—this will ensure both the location and category conditions must be satisfied:

$jobs = Jobs::where('location','like', '%' . $request->location .'%')
            ->where('category', 'like', '%' . $request->category . '%')
            ->get();

Why This Works

Laravel chains where clauses with AND by default, so this query will return only jobs where:

  • The location field contains the value from $request->location (via the like wildcard match)
    AND
  • The category field contains the value from $request->category

This matches exactly what you're looking for with an equivalent of andWhere (note: Laravel doesn't have an andWhere method because where already handles AND logic).

Bonus: Robustness Improvement

If there's a chance $request->location or $request->category might be empty, add checks to avoid unnecessary wildcard matches (which could return all records):

// Start with a base query
$query = Jobs::query();

// Add location condition only if the parameter is filled
if ($request->filled('location')) {
    $query->where('location', 'like', '%' . $request->location . '%');
}

// Add category condition only if the parameter is filled
if ($request->filled('category')) {
    $query->where('category', 'like', '%' . $request->category . '%');
}

// Execute the query
$jobs = $query->get();

内容的提问来源于stack exchange,提问作者Fariha Nuzhat Majumdar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:52:53