skip to Main Content

I’m trying to only return tiers that have options associated to them. My query has a has() method, and a query on my options, but for some reason adding ->has('tiers.options', '>', 0) still returns options that has an empty array. What am I missing here?

$buyers = Buyer::with([
    'tiers.options' => function ($query) {
        $query->where('type', 'private');
    }
])->has('tiers.options', '>', 0)->get();

2

Answers


  1. Have you tried to use whereHas() instead?
    https://laravel.com/docs/10.x/eloquent-relationships#querying-relationship-existence

    It would be something like that if I understand correctly:

    $buyers = Buyer::whereHas('tiers.options', function (Builder $query) {
                $query->where('type', 'private');
            }, '>', 0)->get();
    
    Login or Signup to reply.
  2. how about adding whereHas quary inside of ‘with’
    eg:

    $buyers = Buyer::with([
        'tiers' => function ($query) {
            $query->whereHas('options', function ($query) {
                $query->where('type', 'private');
            });
        }
    ])->get();
    

    here ‘tiers’ that only have options with type private are will fetched.

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