Implementing query scope selects

Posted 1 year ago by bart

Hey guys,

I want to add a select query scope like you can find here:

It would like to select the distance between my model and a passed geo location like this:

public function scopeWithDistanceToPoint($query, $latitude, $longitude)
        return $query->selectRaw("ST_Distance_Sphere(POINT({$longitude}, {$latitude}), POINT(longitude, latitude)) as distanceToPoint");

To get all fields in return I also need to override the newQuery() method of my model:

public function newQuery() {
        return parent::newQuery()->select('objects.*');

What I can do now is:

return Object::take(10)->withDistanceToPoint(0, 0)->get();

Last but not least I only want to get back specific fields from the Eloquent collection like this:

return Object::take(10)->withDistanceToPoint(0, 0)->get(['id', "title->{$this->locale} as title"]);

The problem here is that I don't get the title in the given locale. Instead it returns the entire title JSON object. This is because of the newQuery() method override. Do you have an idea what's wrong here and how to solve this issue?

In the end the get() method does not have any effect. I always get back any field.

Thanks a lot!!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.