binggle's avatar

Is it possible to use SortBy with pagination ?

I have to get manager list using SortBy with Accessors.

Accessors are from relation model.

And I need paginations too.

But SortBy need collection not query.

I can not call SortBy before calling cursorPaginate, I guess.

How can I use Pagination with SortBy ?

source Code is following.

Manager Model


class Manager extends Model
{
    protected $appends = [
        'avg', 'avg_age', 'avg_weight'
    ];

    public function rates()
    {
        return $this->morphMany( Rate::class , 'ratable') ;
    }

    function getAvgAttribute(){
        return $this->rates()->avg('value');
    }

    function getAvgWeightAttribute(){
        return $this->rates()->where('div', 'weight')->avg('value');
    }

    function getAvgAgeAttribute(){
        return $this->rates()->where('div', 'age')->avg('value');
    }


Rate Model

class Rate extends Model
{
    protected $fillable = ['div', 'value'];

    function ratable(){
        return $this->morphTo();
    }
}

Rate Table scheme

public function up()
{
    Schema::create('rates', function (Blueprint $table) {
        $table->id();
        $table->morphs('ratable');
        $table->string('div');
        $table->integer('value');
    });
}

ManagerController


public $hasMorePages ;
public $nextCursor;
public $sorts = ['avg_age', 'avg_weight'];

public function loadManagers($sort =null  )
{
    $query = Manager::query()
            ->sortBy( $sort ); // it makes error 
    
    $managers = $query->cursorPaginate(10, ['*'], 'cursor', Cursor::fromEncoded($this->nextCursor));

    $this->managers->push(...$managers->items());

    if ($this->hasMorePages = $managers->hasMorePages()) {
        $this->nextCursor = $managers->nextCursor()->encode();
    }
}
0 likes
3 replies
Sergiu17's avatar

sortBy is on Collection class, use orderBy, it is on QueryBuilder class

Please or to participate in this conversation.