Jenssen
Jenssen

Reputation: 1871

Laravel query builder join where

I've got this query:

$query = QueryBuilder::for(Advertisement::class)
            ->with('locations');

The locations method on Advertisement looks like this:

public function locations()
{
    return $this->belongsToMany(Location::class, 'advertisement_locations', 'advertisement_id', 'location_id');
}

So a advertisements belongsToMany locations in between is a pivot table called advertisement_locations.

Now I would only get the advertisements between a given long and latitude that's on the locations table.

How could I do this?

Upvotes: 0

Views: 179

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use this:

$query = Advertisement::whereHas('locations', function($query) {
    $query->whereBetween('long', [$min, $max])
        ->whereBetween('latitude', [$min, $max]);
});

Upvotes: 1

Related Questions