Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Illegal operator and value combination Exception on with() with belongsTo() relation

I have a Call Model with a belongsTo() relation as following

class Call extends Model
{
    public function campaign()
    {
        $callStart = $this->call_start;
        return $this->belongsTo('App\Campaign','gsm_number','gsm_number')
        ->where(function($query) use($callStart){
            $query->where('end_date','=','0000-00-00 00:00:00')
                ->orWhere('end_date','>=',$callStart);
        })->where(function($query) use($callStart){
            $query->where('start_date','=','0000-00-00 00:00:00')
                ->orWhere('start_date','<=',$callStart);
        });

    }
}

The logic of this relation is that, each call belongs to a campaign if gsm_numbers in both tables match and call_start from start_date in Campaign is either not set or less than call_start in Call model and end_date in Campaign model is wither not set or it is greater than call_start from Call Model

In Controller I do:

$calls = Call::orderBy('call_start','DESC')->get(); //in simplest form
return view('calls')->with('calls',$calls);

In View for campaigns listing I display campaign information as well using following

@foreach($calls as $call)
      {{ $call->campaign['name'] }}
@endforeach

No issue but I need to perform same issue with ajax calls as well so I need calls data along with campaigns. So I do the following

$calls = Call::with('campaign')->orderBy('call_start','DESC')
            ->get();

if($request->ajax()){
  return $calls
}

In this case I get exception InvalidArgumentException in Builder.php line 464: Illegal operator and value combination.

Exception Stack:

in Builder.php line 464
at Builder->where('end_date', '>=', null, 'or')
at call_user_func_array(array(object(Builder), 'where'), array('end_date', '>=', null, 'or')) in Builder.php line 640
at Builder->where('end_date', '>=', null, 'or') in Builder.php line 656
at Builder->orWhere('end_date', '>=', null) in Call.php line 51
at Call->App\{closure}(object(Builder))
like image 948
Danish Altaf Satti Avatar asked Feb 17 '16 10:02

Danish Altaf Satti


1 Answers

You cannot perform a null comparison on a datetime field. You need to make sure $callStart is not null before adding a where clause ->orWhere('end_date','>=',$callStart);

 $call->campaign['name']

works because $call exists. that is, it contains data. hence $callStart = $this->call_start; will not be null. but when you have

$calls = Call::with('campaign')->orderBy('call_start','DESC')->get();

the query builder calls your relation 'campaign', and evaluates your $callStart = $this->call_start; as null, since Call is not yet a valid model instance, no data is set to to it yet, hence call_start attribute will be null at that point.

like image 161
Ayo Akinyemi Avatar answered Oct 21 '22 22:10

Ayo Akinyemi