使用Laravel DB:Query Builder时,有什么方法可以获取模型对象而不是stdClass对象?

时间:2018-09-07 11:17:01

标签: laravel eloquent query-builder laravel-query-builder

在下面的代码中,我试图获取附近的用户和距离。一切都很好。但是下面的查询以 stdClass对象的形式返回结果,但是我想要用户 Model Object 。有可能吗?

   $collection =  DB::table('users')
        ->join('locations as l', 'users.location_id', '=', 'l.id')
        ->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
        ->having('distances', '<', 32.688888)
        ->orderBy('distances', 'ASC')
        ->get();

输出:

 Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => stdClass Object
                    (

                    )
             )
    )

我想要

 Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => App\Models\User Object
                    (

                    )
             )
    )

1 个答案:

答案 0 :(得分:3)

这是因为您使用的是查询生成器而不是模型。

您应该能够实现以下目标:

var test = results[0].geometry.location;
var marker = new google.maps.Marker({
            position: new google.maps.LatLng(test.lat(), test.lng()),
            animation: google.maps.Animation.DROP,
            map: map,
            icon: image,
            text : text
        });