I have a code block that returns district name of a real estate listing but after I got the first record and try to get the name attribute of the record Laravel executes the query twice.
$district = DB::table('locations')
->whereRaw('st_within((select geom::geometry from listings where id = ' . $this->id . ' )::geometry,locations.geom::geometry) and admin_level = 8')
->select('name')
->first();
if (!is_null($district)) {
return $district->name;
}
I got the district name in first query and try to get the name if district object is not null. But when I write $district->name code Laravel generates duplicate query.
I'm using telescope, when I comment return $district->name line, I see one query when I put it again query dublicates. Looks like it executes the again when I try to get the name.
I'm using GraphQL implementation for Laravel called lighthouse-php. When user asks for district attribute of a real estate listing I need to get the district polygon name which that listing resides. I'm using PostGIS of PostgreSQL and I couldn't find a way of using model relationships between Listing and Locations models.
These two models don't have foreign key relationship in the database, in some way I need to use st_within function of PostGIS to join them. Only way I came up is with Accessors.
Your query uses DB facade it has no idea that there might be any eloquent models. So, if your accessor is being called, its not from the code you showed