laravel Eloquent - 不等于
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28256933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent - where not equal to
提问by aBhijit
I'm currently using the latest Laravel version.
我目前使用的是最新的 Laravel 版本。
I've tried the following queries:
我试过以下查询:
Code::where('to_be_used_by_user_id', '<>' , 2)->get()
Code::whereNotIn('to_be_used_by_user_id', [2])->get()
Code::where('to_be_used_by_user_id', 'NOT IN', 2)->get()
Ideally, it should return all records except user_id = 2
, but it returns blank array. How do I tackle this?
理想情况下,它应该返回除 之外的所有记录user_id = 2
,但它返回空白数组。我该如何解决这个问题?
Code::all()
This returns all 4 records.
这将返回所有 4 条记录。
Code model:
代码模型:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Code extends Model
{
protected $fillable = ['value', 'registration_id', 'generated_for_user_id', 'to_be_used_by_user_id', 'code_type_id', 'is_used'];
public function code_type()
{
return $this->belongsTo('App\CodeType');
}
}
回答by lukasgeiter
Use where
with a !=
operator in combination with whereNull
使用where
了!=
结合运营商whereNull
Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()
回答by Abduhafiz
For where field not empty
this worked for me:
为此,where field not empty
这对我有用:
->where('table_name.field_name', '<>', '')
回答by Yevgeniy Afanasyev
While this seems to work
虽然这似乎有效
Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get();
you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"
您不应该将它用于大表,因为作为一般规则,您的 where 子句中的“或”会停止查询以使用索引。您正在从“密钥查找”到“全表扫描”
Instead, try Union
相反,尝试联盟
$first = Code::whereNull('to_be_used_by_user_id');
$code = Code::where('to_be_used_by_user_id', '!=' , 2)
->union($first)
->get();
回答by Mladen Janjetovic
Or like this:
或者像这样:
Code::whereNotIn('to_be_used_by_user_id', [2])->get();