1

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');
    }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

empCode field is existing inside empmaster table.
@GayanFernando figured that, have you tried the answer ?
Sorry for late reply. I just tested it now and it worked. Thank you so much for your advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.