Help me rewrite Eloquent (Query builder) I have working script. With table:
RECORDS: id|name|text|latitude|longitude
return $builder->whereRaw('ST_Distance(point(latitude, longitude), point('.request('latitude').','.request('longitude').')) < '.$distance);
But I moved latitude/longitude into separate table, so I have:
RECORDS: id|name|text|city_id
CITIES: id|latitude|longitude
How do I rewrite the query builder?
run it against the cities table and not the records table
Where you select the table is not shown here
In Controller I call:
$records = Record::filteredRecords();
return view('searchResults', compact('records'));
Which refers to function in Model:
public static function filteredRecords()
{
return $records = app(Pipeline::class)
->send(Record::query())
->through([
\App\Filters\Distance::class,
...
...
...
...
...
...
\App\Filters\Text::class,
])->thenReturn()->paginate(10, ['*'], 'page');
}
And I want to change only "\App\Filters\Distance::class," which is mentioned in my first post. And my question is about changing that Distance class alone.
you will then have to add a join to the cities table
This seems to work.
return $builder->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);
BUT in returned results, second table overwrites columns of first table. Eg. returned ID is not ID of Records (first table) but ID of Cities (second table).
And overwriting problem seems to be solved by select('records.*')
return $builder->select('records.*')->leftjoin('cities', 'records.city_id', '=', 'cities.id')->whereRaw('ST_Distance(point(cities.latitude, cities.longitude), point(' . request('latitude') . ',' . request('longitude') . ')) < ' . $distance);
I'm marking it solved, although I don't understand this overwriting issue and don't have 100% confidence in this solution.
Please sign in or create an account to participate in this conversation.