Laravel雄辩,其中枢轴为null或小于

时间:2017-08-02 19:37:27

标签: php laravel laravel-5 eloquent laravel-5.4

我在多对多关系的数据透视表中有时间戳字段名为closed 。我想获得关闭的项目为空或小于特定时间的项目。 我尝试了以下方法:

// In model
public function jobEquipments($job, $one = false)
    {
        $nowDt = Carbon::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s'));
        if (!$one){
        return $this->belongsToMany(Equipment::class, 'cavity_actions', 'cavity_id', 'equipment_id')
                ->wherePivot('job_id', $job)
                ->withPivot('created_at','aid')
                ->wherePivot('closed',null)
                ->orWherePivot('closed','<',date('Y-m-d H:i:s'))
                ->orderBy('pivot_created_at', 'desc');
            }
.... 

我还尝试在$nowDt中使用date('Y-m-d H:i:s')代替orWherePivot但是,查询结果没有变化。即看起来没有->orWherePivot('closed','<',date('Y-m-d H:i:s'))子句的相同值。在我的数据库中,我非常确定有足够的记录,其日期时间值小于Now

2 个答案:

答案 0 :(得分:3)

尝试隔离or语句。试试这个:

$this->belongsToMany(Equipment::class, 'cavity_actions', 'cavity_id', 'equipment_id')
                ->wherePivot('job_id', $job)
                ->withPivot('created_at','aid')
                ->where(function ($q) {
                    $q->where('cavity_actions.closed',null)
                      ->orWhere('cavity_actions.closed','<',date('Y-m-d H:i:s'));
                })
                ->orderBy('pivot_created_at', 'desc');

答案 1 :(得分:0)

至少与 PostgreSQL Illuminate \ Database \ Query \ Grammars \ PostgresGrammar )一起使用:

# wherePivotIsNull
->wherePivot(SomeModelName::DELETED_AT, 'is not distinct from', DB::raw('null')

# wherePivotIsNotNull
->wherePivot(SomeModelName::DELETED_AT, 'is distinct from', DB::raw('null')