Search code examples
phplaraveleloquenteager-loading

Laravel eager loading Query issue


I have an issue in below query. The query returns result without running conditions inside eager function. Although we have assigned values for $from_code and $to_code, it doesn't append those inner conditions. it just return all data within empperson table regardless the values assigned $from_code and $to_code .

$empPersons = Empperson::with(['empmaster' => function($query) use ($from_code,$to_code){
    if($from_code !=""){
         $query->where('empmaster.empCode','>=',$from_code);
    }
    if($to_code !=""){
         $query->where('empmaster.empCode','<=',$to_code);
    }
}]);

My Empmaster and Empperson models are as follows.

Empmaster.php

class Empmaster extends Model
{
    protected $table = 'empmaster';

    public function empPerson()
    {
        return $this->hasOne('App\Empperson');
    }

}

Empperson.php

class Empperson extends Model
{
    protected $table = 'empperson';

    public function empMaster()
    {
        return $this->belongsTo('App\Empmaster','empmaster_id','id');
    }
}

Solution

  • So as i understand it you want to condition the Empperson result with the relation exiting within those condition. Then you need to use whereHas, not with

    $empPersons = Empperson::whereHas('empmaster', function($query) use ($from_code,$to_code){
        if($from_code !=""){
             $query->where('empCode','>=',$from_code);
        }
        if($to_code !=""){
             $query->where('empCode','<=',$to_code);
        }
    })->get();
    

    with will only run the condition on the empmaster results. If you still need empmaster relation in the results, you can combine the two.

    $empPersons = Empperson::whereHas('empmaster', function($query) use ($from_code,$to_code){
        if($from_code !=""){
             $query->where('empCode','>=',$from_code);
        }
        if($to_code !=""){
             $query->where('empCode','<=',$to_code);
        }
    })->with(['empmaster' => function($query) use ($from_code,$to_code){
        if($from_code !=""){
             $query->where('empCode','>=',$from_code);
        }
        if($to_code !=""){
             $query->where('empCode','<=',$to_code);
        }
    }])->get();
    

    So actually you can condition Empperson and also get all their Empmaster regardless of the condition.