Skip to content

Commit

Permalink
Added HasGeometryScropes trait and a sample implementation of within
Browse files Browse the repository at this point in the history
  • Loading branch information
ajthinking committed Oct 10, 2017
1 parent 16e77b8 commit a1e1cdf
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/Eloquent/HasGeometryScopes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php
namespace Phaza\LaravelPostgis\Eloquent;

trait HasGeometryScopes
{
public function scopeWithin($query, $geometryColumn, $geometry)
{
// SQL syntax: "ST_Within(geometry A, geometry B)"
// Example: "ST_Within(point::geometry, ST_GeomFromText('POLYGON ((30 10, 20 40, 10 20, 30 10))', 4326 ))"

// Preparing parts
$geometryA = $geometryColumn . "::geometry";
$geometryB = "ST_GeomFromText('" . $geometry->toWKT() . "', " . $this->postgisTypes[$geometryColumn]['srid'] . ")";

// Assumption is made that geometry A and geometry B has the same SRID
return $query->whereRaw("ST_Within(" . $geometryA . "," . $geometryB . ")");
}
}
4 changes: 3 additions & 1 deletion src/Eloquent/PostgisTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Arr;
use Phaza\LaravelPostgis\Eloquent\HasGeometryScopes;
use Phaza\LaravelPostgis\Exceptions\PostgisFieldsNotDefinedException;
use Phaza\LaravelPostgis\Exceptions\PostgisTypesMalformedException;
use Phaza\LaravelPostgis\Exceptions\UnsupportedGeomtypeException;
Expand All @@ -11,7 +12,8 @@

trait PostgisTrait
{

use HasGeometryScopes;

public $geometries = [];
/**
* Create a new Eloquent query builder for the model.
Expand Down

0 comments on commit a1e1cdf

Please sign in to comment.