Query and filter by calculation column with active loading in "Eloquent"

I currently have three models with a working Eloquent request that uses heavy loading. My models have the following relationships:

class Template extends Eloquent {
    public function user() {
        return $this->belongsTo('User');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function profiles() {
        return $this->hasMany('Profile');
    }
    public function templates() {
        return $this->hasMany('Template');
    }
}

class Profile extends Eloquent {
    public function user() {
        return $this->belongsTo('User');
    }
}

And my working request looks like this:

$templates = Template::with('user', 'user.profiles')
    ->where('public', '=', true)
    ->whereIn('type', $search_types)
    ->where('user_id', '!=', $user->id)
    ->paginate(8);

It seems to work fine, but I need to add one more thing, and it was very difficult for me to do this. I need to modify this query to take into account the user distance of the template from the current user using existing columns latand longin the table user. I want the query to return patterns whose users are within 25 miles of the current user (perfectly ordering distance, but this part is optional).

:

$templates = Template::with(array('user' => function($query) use($user) {
        $query->select('*')->selectRaw('(3959 * acos(cos(radians(?)) * cos(radians(lat)) * cos(radians(long) - radians(?)) + sin(radians(?)) * sin(radians(lat)))) AS distance', array($user->lat, $user->long, $user->lat));
    }, 'user.profiles' => function($query) {
        $query
    }))
    ->where('public', '=', true)
    ->whereIn('type', $search_types)
    ->where('user_id', '!=', $user->id)
    ->having('distance', '<=', 25)
    ->orderBy('distance')
    ->paginate(8);

, distance , having. , , , , 25 , .

Eloquent , ?

+4
1

( ), , , :

$templates = Template::with('user', 'user.profiles')
    ->where('public', '=', true)
    ->whereIn('type', $search_types)
    ->where('user_id', '!=', $user->id)
    ->whereHas('user', function($query) use($user, $distance) {
        $query->whereRaw('(3959 * acos(cos(radians(?)) * cos(radians(location_lat)) * cos(radians(location_long) - radians(?)) + sin(radians(?)) * sin(radians(location_lat)))) <= ?', array($user->location_lat, $user->location_long, $user->location_lat, $distance));
    })
    ->paginate(8);
+5

All Articles