简体   繁体   中英

How to return an array using Laravel Eloquent select?

I have this class

<?php

namespace App\Models\Tables;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

class ZipCode extends Model
{
    protected $table      = 'zip';
    public    $timestamps = false;
    protected $fillable   = [
        'latitude',
        'longitude',
    ];

    public static function radiusSearch($lat, $lng)
    {
        $circle_radius = 3959;
        $subQuery      = '(SELECT *, (' . $circle_radius . ' * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) * cos(radians(longitude) - radians(' . $lng . ')) + sin(radians(' . $lat . ')) * sin(radians(latitude)))) AS distance FROM zip) AS distances';

        $result = ZipCode::select('*')
            ->from(ZipCode::raw($subQuery))
            ->limit(20);

        var_dump($result);

        return $result;
    }
}

when I call radiusSearch(...) I get a Illuminate\\Database\\Eloquent\\Builder object and not the actual result

$result->get() doesn't work, I get Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string

This generic query works just fine ZipCode::where('zip', '11111')->get() just not the above one

Any ideas?

EDIT: the $result returns something like this:

object(Illuminate\Database\Eloquent\Builder)[170]
  protected 'query' => 
    object(Illuminate\Database\Query\Builder)[164]
      public 'connection' => 
        object(Illuminate\Database\MySqlConnection)[166]
          protected 'pdo' => 
            object(PDO)[175]
            ...
  protected 'model' => 
    object(App\Models\Tables\ZipCode)[171]
      protected 'table' => string 'zip' (length=9)
      public 'timestamps' => boolean false
      ...

If I do $result->getModel()->get()->toArray() this returns all results from the table

As you have already seen the code

$result = ZipCode::select('*')
        ->from(ZipCode::raw($subQuery))
        ->limit(20);

will return a Builder object which represents you query. You need to call ->get() to have the builder actually execute your query and return the results

$result = ZipCode::select('*')
        ->from(ZipCode::raw($subQuery))
        ->limit(20)->get();

Here is the solution I came up with based on some other community answers

public static function getClosestCities($lat, $lng, $city, $distance = 20, $limit = 20)
{
    $coordinates = ['latitude' => $lat, 'longitude' => $lng];
    $cares       = self::scopeIsWithinMaxDistance(ZipCode::raw('select *'), $coordinates, $distance, $city)->limit($limit)->get();

    return $cares ? $cares->toArray() : null;
}


public static function scopeIsWithinMaxDistance($query, $coordinates, $radius = 5, $city)
{
    $haversine = "(3961 * acos(cos(radians(" . $coordinates['latitude'] . ")) 
                * cos(radians(`latitude`)) 
                * cos(radians(`longitude`) 
                - radians(" . $coordinates['longitude'] . ")) 
                + sin(radians(" . $coordinates['latitude'] . ")) 
                * sin(radians(`latitude`))))";

    return $query->select('*')
        ->selectRaw("{$haversine} AS distance")
        ->orderByRaw("{$haversine} asc")
        ->whereRaw("{$haversine} < ?", [$radius])
        ->groupBy("city");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM