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

风格不统一 提交于 2019-12-10 15:26:49

问题


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))

回答1:


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.



来源:https://stackoverflow.com/questions/35454512/laravel-illegal-operator-and-value-combination-exception-on-with-with-belongst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!