skip to Main Content

I have something strange going on. I am trying to query with a whereNull and also a where statement. When i just use the whereNull it returns results, but as soon as I add the where statement, nothing gets returned even though there should be 2 results.

$user
    ->shoePurchases()
    ->whereNull('completed_at')
    ->where('status', '!=', 'failed')
    ->get();

The shoePurchases relationship is a simple hasMany

2

Answers


  1. You can do these things in order to find the problem

    Review the data: Ensure that there exist shoe purchases which are not marked as "failed" and are yet to be completed. To perform this check, execute the following query directly on your database:

    SELECT * FROM shoe_purchases WHERE completed_at IS NULL AND status != 'failed';
    

    Remove the where clause for the status and see if you get any results. This will help you determine if the issue is with the whereNull or the where clause for the status.

    $user
        ->shoePurchases()
        ->whereNull('completed_at')
        ->get();
    

    Use the orWhere method: Instead of using multiple where clauses, use the orWhere method to retrieve shoe purchases that are not completed or have a status other than "failed".

    $user
        ->shoePurchases()
        ->where(function($query) {
            $query->whereNull('completed_at')
                  ->orWhere('status', '!=', 'failed');
        })
        ->get();
    
    Login or Signup to reply.
  2. In this case, I guess All purchases with status != ‘failed’ have completed_at not null

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search