简体   繁体   English

Laravel从查询构建器获取某些列

[英]Laravel get certain column from Query builder

I have a query as follows: 我有一个查询如下:

$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();  

I get Cardinality violation error which I know is because of nested query. 我收到Cardinality violation错误,我知道这是因为嵌套查询。
I need to get only id column from nested query but I can't. 我只需要从嵌套查询中获取id列,但我不能。
I have tried using get(['id']) but it didn't work. 我尝试使用get(['id'])但没有用。
I even tried using array_map and returing sth like array_map(function ($venue){return $venue->id}, $venues); 我什至尝试使用array_map并像array_map(function ($venue){return $venue->id}, $venues);那样重做某事array_map(function ($venue){return $venue->id}, $venues); but I get the same error too. 但我也遇到同样的错误。
How can I solve get only id column from query builder as an array. 如何解决从查询生成器仅获取id列作为数组的问题。 How can I pass 我该如何通过

This is a just a guess, but your nested query function is not supposed to be executed by ->get() and you are not specifying the id column. 这只是一个猜测,但是您的嵌套查询函数不应由->get()执行,并且您未指定id列。 Try this: 尝试这个:

$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();

Edit: use query scope and calculated attributes 编辑:使用查询范围和计算出的属性

$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 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 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');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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