当表中不存在列时,如何将paginate()与having()子句一起使用

时间:2013-10-13 19:37:20

标签: laravel laravel-4

我有一个棘手的案例......

以下数据库查询不起作用:

DB::table('posts')
->select('posts.*', DB::raw($haversineSQL . ' as distance'))
->having('distance', '<=', $distance)
->paginate(10);

它失败并显示消息:列距离不存在。

当paginate()尝试使用

计算记录时,会发生错误
select count(*) as aggregate from {query without the column names}

当列名被剥离时,距离未知且引发异常。

在这种情况下,某人是否有能够使用分页的工作?

由于

7 个答案:

答案 0 :(得分:7)

这对查询构建器来说有点问题,因为在进行聚合调用时会丢弃所有选择(如count(*))。现在的make-do解决方案是手动构建pagniator。

$query = DB::table('posts')
    ->select(DB::raw('(c1 - c2) as distance'))
    ->having('distance', '<=', 5);

$perPage = 10;
$curPage = Paginator::getCurrentPage(); // reads the query string, defaults to 1

// clone the query to make 100% sure we don't have any overwriting
$itemQuery = clone $query;
$itemQuery->addSelect('posts.*');
// this does the sql limit/offset needed to get the correct subset of items
$items = $itemQuery->forPage($curPage, $perPage)->get();

// manually run a query to select the total item count
// use addSelect instead of select to append
$totalResult = $query->addSelect(DB::raw('count(*) as count'))->get();
$totalItems = $totalResult[0]->count;

// make the paginator, which is the same as returned from paginate()
// all() will return an array of models from the collection.
$paginatedItems = Paginator::make($items->all(), $totalItems, $perPage);

使用MySQL测试以下架构:

Schema::create('posts', function($t) {
    $t->increments('id');
    $t->integer('c1');
    $t->integer('c2');
});

for ($i=0; $i < 100; $i++) { 
    DB::table('posts')->insert([
        'c1' => rand(0, 10),
        'c2' => rand(0, 10),
    ]);
}

答案 1 :(得分:4)

使用Eloquent,我知道你可以将列传递给paginator,如下所示:

Post::having('distance','<=', $distance)
   ->paginate(10, array('*', DB::raw($haversineSQL . ' as distance')));

不确定它是否在没有Eloquent的情况下有效,但您可以尝试一下。

答案 2 :(得分:4)

您可以在WHERE部分计算距离:

DB::table('posts')
    ->whereRaw($haversineSQL . '<= ?', [$distance])
    ->paginate(10);

如果您的应用需要distance值,则必须计算两次:

DB::table('posts')
    ->select('posts.*', DB::raw($haversineSQL . ' as distance'))
    ->whereRaw($haversineSQL . '<= ?', [$distance])
    ->paginate(10);

答案 3 :(得分:3)

这不是一个令人满意的答案,但如果你只需要显示简单的&#34; Next&#34;和&#34;以前&#34;您的分页视图中的链接,您可以使用simplePaginate方法。它将执行更有效的查询,如果您使用having,它将不会崩溃。

DB::table('posts')
->select('posts.*', DB::raw($haversineSQL . ' as distance'))
->having('distance', '<=', $distance)
->simplePaginate(10);

答案 4 :(得分:2)

您可以使用手动分页作为having表现特殊的分页类。

$posts = DB::table('posts')
    ->select('posts.*', DB::raw($haversineSQL . ' as distance'))
    ->having('distance', '<=', $distance)
    ->get();

// Items per page
$perPage = 10;
$totalItems = count($posts);
$totalPages = ceil($totalItems / $perPage);

$page = Input::get('page', 1);

if ($page > $totalPages or $page < 1) {
    $page = 1;
}

$offset = ($page * $perPage) - $perPage;

$posts = array_slice($posts, $offset, $perPage);

$posts = Paginator::make($posts, $totalItems, $perPage);


dd($posts);

答案 5 :(得分:2)

这是范围实现 Haversine公式搜索,并对速度进行了额外优化,即documented here

我希望有更简洁的方法从查询对象获取原始SQL,但不幸的是Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage, (sum(FMUM.AI_NormalizedUsage / sum(FMUM.TotalUnits)) 在替换占位符之前返回SQL,所以我依赖于几个toSql()调用。它不是太糟糕,但我希望它更清洁。

代码假设您的表格中包含*Rawlat列。

lng

这可以这样使用:

const DISTANCE_UNIT_KILOMETERS = 111.045;
const DISTANCE_UNIT_MILES      = 69.0;

/**
 * @param $query
 * @param $lat
 * @param $lng
 * @param $radius numeric
 * @param $units string|['K', 'M']
 */
public function scopeNearLatLng($query, $lat, $lng, $radius = 10, $units = 'K')
{
    $distanceUnit = $this->distanceUnit($units);

    if (!(is_numeric($lat) && $lat >= -90 && $lat <= 90)) {
        throw new Exception("Latitude must be between -90 and 90 degrees.");
    }

    if (!(is_numeric($lng) && $lng >= -180 && $lng <= 180)) {
        throw new Exception("Longitude must be between -180 and 180 degrees.");
    }

    $haversine = sprintf('*, (%f * DEGREES(ACOS(COS(RADIANS(%f)) * COS(RADIANS(lat)) * COS(RADIANS(%f - lng)) + SIN(RADIANS(%f)) * SIN(RADIANS(lat))))) AS distance',
        $distanceUnit,
        $lat,
        $lng,
        $lat
    );

    $subselect = clone $query;
    $subselect
        ->selectRaw(DB::raw($haversine));

    // Optimize the query, see details here:
    // http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

    $latDistance      = $radius / $distanceUnit;
    $latNorthBoundary = $lat - $latDistance;
    $latSouthBoundary = $lat + $latDistance;
    $subselect->whereRaw(sprintf("lat BETWEEN %f AND %f", $latNorthBoundary, $latSouthBoundary));

    $lngDistance     = $radius / ($distanceUnit * cos(deg2rad($lat)));
    $lngEastBoundary = $lng - $lngDistance;
    $lngWestBoundary = $lng + $lngDistance;
    $subselect->whereRaw(sprintf("lng BETWEEN %f AND %f", $lngEastBoundary, $lngWestBoundary));

    $query
        ->from(DB::raw('(' . $subselect->toSql() . ') as d'))
        ->where('distance', '<=', $radius);
}

/**
 * @param $units
 */
private function distanceUnit($units = 'K')
{
    if ($units == 'K') {
        return static::DISTANCE_UNIT_KILOMETERS;
    } elseif ($units == 'M') {
        return static::DISTANCE_UNIT_MILES;
    } else {
        throw new Exception("Unknown distance unit measure '$units'.");
    }
}

生成的SQL看起来大概如下:

        $places->NearLatLng($lat, $lng, $radius, $units);
        $places->orderBy('distance');

答案 6 :(得分:0)

有更好的方法,也可以使用链接:

        $curPage = \Illuminate\Pagination\Paginator::resolveCurrentPage();
        $total = $model->get()->count();
        $items = $model->forPage($curPage, $showPerPag)->get();
        $paginated = new \Illuminate\Pagination\LengthAwarePaginator($items, $total, $showPerPage, $curPage, ['path' => request()->url(), 'query' => request()->query()]);