【问题标题】:Laravel eloquent where pivot null or less thanLaravel 雄辩,其中枢轴为空或小于
【发布时间】:2018-01-10 04:40:00
【问题描述】:

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

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

我也尝试在orWherePivot中使用$nowDt而不是date('Y-m-d H:i:s')但是查询结果没有变化。即它看起来像没有 -&gt;orWherePivot('closed','&lt;',date('Y-m-d H:i:s')) 子句的相同值。在我的数据库中,我很确定有足够的记录关闭日期时间值小于Now

【问题讨论】:

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


    【解决方案1】:

    尝试隔离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');
    

    【讨论】:

    • Call to undefined method Illuminate\Database\Query\Builder::orWherePivot()
    • 好的,尝试使用 Where 和 orWhere。我已经编辑了答案
    • 最后一次编辑有效,但它返回的结果与我认为没有隔离的代码相同。
    • 对不起,我忘了dd() 正确输出您的代码。它工作正常人。谢谢。
    【解决方案2】:

    至少适用于 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')
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2020-10-26
      • 2017-05-24
      • 1970-01-01
      • 2019-07-24
      • 2018-07-05
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      相关资源
      最近更新 更多