select coordinates at other tables

 ̄綄美尐妖づ 提交于 2019-12-11 06:56:37

问题


I want to get all nearest items, the coordinates are saved at listings table. items and listings are many to many relationship. Then it will be sorted either by distance or low to high price.

 $items = Item::with('listings')
               ->select('*');
if($request->sortby == 'distance'){
        $items->distance($lat,$lng);
      }
if($request->sortby == 'low'){
        $items->groupBy('listings.id')
              ->orderBy('items.price');
      }
$items = $items->paginate(10);

This is my Item model for distance

public function scopeDistance($query, $lat, $lng) {
        return $query->addSelect(DB::Raw('(3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( listings.latitude ) ) * cos( radians( listings.longitude ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(listings.latitude) ) ) ) AS distance'))
                  ->orderBy('distance');
    }

this requires listings.latitude and listings.longitude which are saved in listings table. The error is

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'listings.latitude' in 'field list'

and if sorted low to high price

Column not found: 1054 Unknown column 'listings.id' in 'group statement'

how to access/select coordinates and listings for these two sorts?


回答1:


Your Items is collection of Item not a model, thus you cannot execute distance method on this object. You have to use foreach and find distance between user position and each of the Items.

foreach($items as $item) {   
    $distance=$item->distance($userPosition);   
}

Now in the distance method you will calculate distance between user position and Item.

Secondly change $items->groupBy('listings.id') to be $items->groupBy('listing_id') where listing_id is field on items table




回答2:


You may use join instead of eager loading here.

$items = Item::join('listings','listings.item_id','=','items.id')
               ->select('*');

Then use your logic here.

if($request->sortby == 'distance'){
        $items->distance($lat,$lng);
      }
if($request->sortby == 'low'){
        $items->groupBy('listings.id')
              ->orderBy('items.price');
      }
$items = $items->paginate(10);


来源:https://stackoverflow.com/questions/45604577/select-coordinates-at-other-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!