Laravel Eloquent的"WHERE NOT IN"

214

我在使用 Laravel Eloquent ORM 写查询时遇到了困难。

我的查询如下:

SELECT book_name,dt_of_pub,pub_lang,no_page,book_price  
FROM book_mast        
WHERE book_price NOT IN (100,200);

现在我想将这个查询转换为 Laravel Eloquent。

13个回答

461

查询构建器:

DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();

Eloquent:

SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();

36
get中,select可以被一个数组所替代。 - Marwelln
2
@Marwelln,是的,但它不能处理复杂的查询。例如,使用addSelect方法时。 - Orange-Man

39

您也可以这样使用WhereNotIn

ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);

这将返回具有特定字段的记录集合


18

在我添加方法->toArray()到结果之前,我在制作子查询时遇到了问题,希望这能帮助不止一个人,因为我花了很多时间寻找解决方案。

示例

DB::table('user')                 
  ->select('id','name')
  ->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
  ->get();

2
使用->pluck('id_user')而不是->toArray()对我有效。 - CESILICON
这种方法不是最优的,使用子查询更好。DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray()执行了完整的数据库查询并检索结果。在这种情况下,有两个SQL查询调用到数据库。建议改用->whereNotIn('id', function($q){ $q->table('curses')->select('id_user')->where('id_user', '=', $id); }) - Bill L.

12

查询构建器:

    DB::table('book_mast')
->select('book_name','dt_of_pub','pub_lang','no_page','book_price')
    ->whereNotIn('book_price', [100,200])->get();

雄辩:

BookMast::select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();

谢谢您的回答,但它或多或少是现有答案的重复。 - shaedrich
是的,但这就是 Laravel 中 whereNotIn 的用法。无论如何,感谢您的评论。 - samzna

5
实现 whereNotIn 的动态方式:
 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

4
你的示例过于复杂。User::orderBy('name', 'DESC')->where('status', '!=',0)->get() - Adsy2010

4
您可以使用此示例动态调用Where NOT IN
$user = User :: where('company_id','=',1) - > select('id) - > get() - > toArray();

$otherCompany = User :: whereNotIn('id',$ user) - > get();

2
您可以按照以下方式使用WhereNotIn
$category=DB::table('category')
          ->whereNotIn('category_id',[14 ,15])
          ->get();`enter code here`

1
您可以做以下事情。
DB::table('book_mast') 
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')  
->whereNotIn('book_price',[100,200]);

1

这是我针对 Laravel 7 的工作变体

DB::table('user')                 
  ->select('id','name')
  ->whereNotIn('id', DB::table('curses')->where('id_user', $id)->pluck('id_user')->toArray())
  ->get();

0

或者尝试在Laravel中使用pluck 在这里

DB::table('user')                 
          ->select('id','name')
          ->whereNotIn('id', DB::table('curses')->where('id_user', '=', $id)->pluck('user_id'))
          ->get();  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接