aarondfrancis / fast-paginate

A fast implementation of offset/limit pagination for Laravel.
MIT License
1.21k stars 56 forks source link

Using aliased columns does not work #21

Closed j3j5 closed 2 years ago

j3j5 commented 2 years ago

When using alias for columns on the select and ordering by them, the package fails to include the aliased column into the first query.

The issue comes from the column name being wrapped when collecting the orders but not wrapping it when comparing with the actual columns from the select.

A code example where this fails, on a database with an articles table, a categories table, and an article_category pivot table to store the relationships between Article and Category would be:

$articlesQuery = Article::select('articles.*')
    ->join('article_category', 'article_category.article_id', '=', 'articles.id')
    ->where('article_category.category_id', 1);

// Use the article_category column instead to speed up things
$column = 'article_category.article_id';
$columnAlias = 'category_article_id';
$articlesQuery->addSelect("$column as $columnAlias");
$articlesQuery->reorder($columnAlias, 'desc');

$articlesQuery->fastPaginate();

The above code throws the following exception:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_article_id' in 'order clause' (SQL: select `articles`.`id` from `articles` inner join `article_category` on `article_category`.`article_id` = `articles`.`id` where `article_category`.`category_id` = 1 order by `category_article_id` desc limit 15 offset 0)'

I'm submitting a MR to fix it which should be #22.