Search code examples
phpsqllaravel-5.3

Where clause query using Laravel Eloquent


I am having this code working correctly $sector = Sector::where('ref_id', $sectorId)->with('offers.provider')->first(); which has been changed to the code below for more flexibility and more understanding of what I want to do:

$sector = Sector::where('ref_id', '$sectorId')
->with(
    [
        'offers' => function($query) {
            $query->with(
                [
                    'provider' => function($query) {
                        $query->select('name');
                    }
                ]
            );
        }
    ]
)
->first();

So here we are taking a sector, the offers link to this sector and under each offer, we are taking the linked provider. Now, providers are having a status which is either 0 or 1. So based on my code above, is there a way to retrieve ONLY offers which are having providers with the status of 1 ?

Kindly help me solve this problem.


Solution

  • You can use whereHas - which is specifically designed to work for scenarios like this. The example from the docs:

    If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment:

    // Retrieve all posts with at least one comment containing words like foo%
    $posts = Post::whereHas('comments', function ($query) {
        $query->where('content', 'like', 'foo%');
    })->get();
    

    Don't let the snippet fool you, it'll work perfectly well inside a closure as you have above.