php - Laravel 从查询构建器获取特定列

标签 php mysql sql arrays laravel

我有一个查询如下:

$locations = Location::select(DB::raw("* , 1000*distance AS distance"))
        ->whereIn("id", function ($q) use ($userLat, $distance, $userLng, $cityId)
        {
            $venues = $q->select('*')
                ->from('locations')
                ->where('city_id', $cityId)
                ->havingRaw("lat BETWEEN $userlat AND $userlat+10")
                ->havingRaw("lng BETWEEN $userLng AND $userlng+10")
                ->get();
         })
        ->havingRaw('distance <' . $distance)
        ->orderBy('distance')
        ->take($limit)
        ->get();  

我收到基数违规错误,我知道这是由于嵌套查询造成的。
我只需要从嵌套查询中获取id 列,但我不能。
我尝试过使用 get(['id']) 但没有成功。
我什至尝试使用 array_map 并返回诸如 array_map(function ($venue){return $venue->id}, $venues); 但我也遇到了同样的错误.
如何解决从查询生成器中仅获取 id 列作为数组的问题。 怎么才能通过

最佳答案

这只是一个猜测,但是您的嵌套查询函数不应该由 ->get() 执行,并且您没有指定 id 列。试试这个:

$locations = Location::select(DB::raw("* , 1000*distance AS distance"))
    ->whereIn("id", function ($q) use ($userLat, $distance, $userLng, $cityId)
    {
        $venues = $q->select('id')
            ->from('locations')
            ->where('city_id', $cityId)
            ->havingRaw("lat BETWEEN $userlat AND $userlat+10")
            ->havingRaw("lng BETWEEN $userLng AND $userlng+10")
            ;
     })
    ->havingRaw('distance <' . $distance)
    ->orderBy('distance')
    ->take($limit)
    ->get();

编辑:使用查询范围和计算属性

$lat = ''; // latitude
$lng = ''; // longitude

$distance = 5; // distance amount

$radius = compact('lat', 'lng', 'distance');

$targets = Location::withinRadius($radius)
    ->with('city')
    ->get()
    ->map(function ($value, $key) use ($lat, $lng) {
        return $value->target = [$lat, $lng];
    })
    ->filter(function ($value, $key) use ($distance) {
        return $value->distance < $distance;
    })
    ;

app/Location.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Location extends Model
{
    // Add the attributes for inclusion in toArray() and toJson()
    protected $appends = ['target', 'distance'];

    // Hold the target Location
    protected $_target = null;

    // ... other model code

    /**
     * Return the query with radius limits
     */
    public function scopeWithinRadius($q, $radius)
    {
        $target_lat = $radius['lat'];
        $target_lng = $radius['lng'];
        $distance = $radius['distance'];

        $target_lat_range = [$target_lat + $this->adjustLat($distance * -1), $target_lat + $this->adjustLat($distance)];
        $target_lng_range = [$target_lng + $this->adjustLng($distance * -1), $target_lng + $this->adjustLng($distance)];

        return $q->havingRaw("lat BETWEEN " . $target_lat_range[0] ." AND ".$target_lat_range[1])
            ->havingRaw("lng BETWEEN " . $target_lng_range[0] ." AND ".$target_lng_range[1])
        ;
    }

    /**
     * Return the amount to adjust latitude by for the given distance
     */
    private function adjustLat($distance)
    {
        // return latitude adjustment amount
    }

    /**
     * Return the amount to adjust longitude by for the given distance
     */
    private function adjustLng($distance)
    {
        // return longitude adjustment amount
    }

    /**
     * Get the Target coordinates
     */
    public function getTargetAttribute()
    {
        return $this->_target;
    }

    /**
     * Get the Target latitude
     */
    public function getTargetLatAttribute()
    {
        return $this->_target[0];
    }

    /**
     * Get the Target longitude
     */
    public function getTargetLngAttribute()
    {
        return $this->_target[1];
    }

    /**
     * Set the Target of the Location
     */
    public function setTargetAttribute($value)
    {
        // check if value is a Location
        if ($value instanceof Location) {
            $value = [$value->lat, $value->lng];
        }

        $this->_target = $value;
    }

    /**
     * Determine the Distance from target
     */
    public function getDistanceAttribute()
    {
        $lat1 = $this->lat;
        $lng1 = $this->lng;
        $lat2 = $this->target_lat;
        $lng2 = $this->target_lng;

        // calculate the distance between Location and points            
        // ... $distance = ...

        return $distance;
    }

}

app/City.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    // ... other model code

    /**
     * Get the Location of the City
     */
    public function location()
    {
        return $this->hasMany('App\Location');
    }
}

关于php - Laravel 从查询构建器获取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203787/

相关文章:

mysql - 选择 order By 并限制 3,000,000 行表的慢速

php - 无法使用 PHP 插入 MySQL 表

php - 如何隐藏 div 内容并仅在单击按钮时显示?

php - mysql中的单词相似度/相似度

mysql - IF on WHERE 子句

SQLite3限制内连接使用时间

mysql - 如何获得列中各组数字的平均值?继续获取 "Error 1111:Invalid use of Group Functions"

php - 标题中数据库中的行,设置为显示在所有页面中

PHP - Curl - 带有应用程序/八位字节流的多部分/表单数据用于空白文件

php - Laravel 4 leftJoin mySQL 语句未正确返回