Search code examples
phplaravelmongodbeloquentlumen

Where and WhereIn and WhereRaw not working for boolean values in lumen with mongodb


I am having collection of employee associated with company

use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Employee extends Eloquent
{
    protected $casts = [
        'has_pp'       => 'Boolean',
        'has_eal'      => 'Boolean',
        'support'     => 'String',
        'has_cin'      => 'Boolean',
        'has_lac'      => 'Boolean'
    ];

    protected $fillable = [
        'first_name',
        'last_name',
        'has_pp',
        'has_eal',
        'support',
        'has_cin',
        'has_lac'
    ];

    public function company() {
        return $this->belongsTo(Company::class);
    }
}

My company collection is like

class Company extends Eloquent 
{
    protected $fillable = [
        'name',
        'total_employee',
        'active',
    ];

    public function employee() {
        return $this->hasMany(Employee::class);
    }
}

I want to filter out employee on the basis of values of has_pp and has_lac for which I am doing the query below

$filterdata = Company::find($request->company_id);
if($request->has('pp')) {
   $filterdata = $filterdata->whereHas('employee',function ($query) use($request){
                    $query->whereIn('has_pp',$request->pp);
                });
}
$filterdata = $filterdata->get();

Now the above query gives me blank array as o/p, here $request->pp is array type ex:- [true,false], whereIn works okay will all other values but cause issue with value which are boolean type. I had also tried some other query like

$filterdata = $filterdata->whereHas('employee',function ($query) use($request){
                    $query->whereRaw(['has_pp'=>['$eq'=>false]]);
                });
$filterdata = $filterdata->whereHas('employee',function ($query) use($request){
                    $query->where('has_pp','=',false);
                });

i also had hardcoded direct values, but did'nt worked.
Pls ignore typing error
```
currently i am using 
"jenssegers/mongodb": "3.5"
lumen 5.8

Solution

  • after a long search i was able to found the solution for my problem.

    1. monogdb uses different type queries for filtering for boolean values.for better understanding you can read this article. https://www.tutorialspoint.com/mongodb-query-for-boolean-field-as-not-true

    2. whereRaw works in case when directly searched with employee collection , but when we use it after whereHas query it does not worked.

    so the query which works for me

    $filterdata = Employee::whereRaw(['has_pp'=>['$eq'=>false]]);
    or
    $filterdata = Employee::whereRaw(['has_pp'=>['$ne'=>false]]);
    
    

    $eq = equalto , $ne = not equal to syntax as per mongodb.

    But still i am not able to understand the reason behind why WhereRaw does not works with WhereHas as per my previous query. if you guys understand the reason please do share.