Since three days I'm working on following problem:
protected function getTableQuery(): Builder
{
return User::
where('age','>',21)
->AppendDistanceTo(
$this->city->geo->long,
$this->city->geo->lat,
**lo**,
**la**,
);
}
The Model User has user_id and a id for the city city_id.
In the model City there is longitude and latitude for each city_id. How can I get the longitude and latitude in the query above, für lo and la from the related Model?
Thank you very much for helping!
I want to show the distance from a selected city ( $this->city->geo->long,$this->city->geo->lat)
to the city, where the user lives.
CodePudding user response:
Given your User
model has a city relationship, and the City
model has a geo
relationship, you could eager load the city relation like so:
User::where('age', '>', 21)
->with('city.geo')
Then, $user->city->geo->long
CodePudding user response:
Thank you, but I think, there is a misunderstanding, due my english.
class User extend Model
{
public function scopeAppendDistanceTo(Builder $query, $long_choice, $lat_choice,$long_destination, $lat_destination): Builder
{
return $query->selectRaw("
*,
Round(ST_Distance_Sphere(
point(?,?),
point(?, ?)
)/1000,0) as distance
", [
$long_choice,
$lat_choice,
$long_destination,
$lat_destination,
]);
}
public function city()
{
return $this->hasOne(City::class, 'city_id', 'city_id_user');
}
class City extends Model
{
'standard'
}
User::where('age', '>', 21)
->AppendDistanceTo(
$this->city->geo->long, // user's choice in selection
$this->city->geo->lat, // user's choice in selection
here I need the long from CityModel related to city_id_user in UserModel,
here I need the lat from CityModel related to city_id_user in UserModel,
So: I want to display the distance from a chosen city to the city in a users-data-set.
Thanks a lot.