Framework: orWhereHas on relation with whereHas

Created on 4 Jun 2018  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 5.6.7
  • PHP Version: 7.2.2
  • Database Driver & Version:

Description:

I'm experiencing a problem with the orWhereHas method using with a relation.
It looks like an old bug:
https://github.com/laravel/framework/issues/7207

Steps To Reproduce:

time() is a hasMany() relationship.

$times = $user->time()
        ->whereHas('sample_relation', function ($query) {
        $query->whereDate('created_at', date('Y-m-d', time()));
        })
        ->orWhereHas('sample_relation_2', function($query) {
        $query->whereDate('created_at', date('Y-m-d', time()));
        })
        ->get();

Most helpful comment

The problem is that AND has precedence over OR. You have to nest the constraints:

$times = $user->time()
    ->where(function ($query) {
        $query->whereHas('sample_relation', function ($query) {
            $query->whereDate('created_at', date('Y-m-d', time()));
        })
        ->orWhereHas('sample_relation_2', function($query) {
            $query->whereDate('created_at', date('Y-m-d', time()));
        });
    })
    ->get();

All 4 comments

The problem is that AND has precedence over OR. You have to nest the constraints:

$times = $user->time()
    ->where(function ($query) {
        $query->whereHas('sample_relation', function ($query) {
            $query->whereDate('created_at', date('Y-m-d', time()));
        })
        ->orWhereHas('sample_relation_2', function($query) {
            $query->whereDate('created_at', date('Y-m-d', time()));
        });
    })
    ->get();

Describe your issue properly.

What is expected and what your query actually do.
Is sample_relation_2 different from sample_relation ?

@staudenmeir Thank you for the answer.

@rSammy Yes, sample_relation_2 is different. The problem is solved.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Fuzzyma picture Fuzzyma  路  3Comments

felixsanz picture felixsanz  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

ghost picture ghost  路  3Comments

YannPl picture YannPl  路  3Comments