欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 不为空 Eloquent OR WHERE IS NOT NULL orWhereNotNull whereNotNull 有大用

I am using the Laravel Administrator package from frozennode. Long story short, I'm running into issues when displaying results that are soft-deleted. I'm trying to override the default query:

select * from `scripts` where `scripts`.`deleted_at` is null group by `scripts`.`id`

To display both deleted results and non-deleted, somehow hacking away. It's not the most elegant solution but I don't see any other way to do it. So, my goal is to do this:

select * from `scripts` where `scripts`.`deleted_at` is null or `scripts`.`deleted_at` is not null group by `scripts`.`id`

Unfortunately I don't know how to use orWhere() with 'is not null'. After researching a bit, I tried it with a raw SQL block, like this:

'query_filter'=> function($query) {
    $query->orWhere(DB::raw('`scripts`.`deleted_at` is not null'));
},

But I ended up with an extra piece of SQL resulting of not including the second parameter in orWhere():

select * from `scripts` where `scripts`.`deleted_at` is null or `scripts`.`deleted_at` is not null **is null** group by `scripts`.`id`

How can I fix this?

share
 

3 Answers 正确答案

Just add withTrashed:

'query_filter'=> function($query) {
    $query->withTrashed();
},

Source

Update

In that case, you can probably just add a orWhereNotNull() call:

'query_filter'=> function($query) {
    $query->orWhereNotNull('deleted_at');
},
share
 
   
Unfortunately that doesn't work. I'm getting a Call to undefined method Illuminate\Database\Query\Builder::withTrashed() error. – Anonymous Oct 13 '14 at 20:37
 
 

If you want to search deleted record (Soft Deleted Record), don't user Eloquent Model Query.
Instead use Db::table query
e.g
Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();


普通分类: