3

Say my User model's balance attribute from getBalanceAttribute() returns the sum of amount from user's Transaction model, how can this be orderable in the Datatable?

User.php

public function transactions()
{
  return $this->hasMany(\App\Transaction::class);
}

public function getBalanceAttribute()
{
  return $this->transactions()->sum('amount');
}

Transaction.php

public function user()
{
  return $this->belongsTo(\App\User::class);
}

UserCrudController.php

...
public function setup()
{
  ...
  $this->crud->addColumn(
  [
    'name' => "balance",
    'label' => "Balance",
    'type' => 'number',
    // Here the column is clickable but is not actually sorted.
    'orderable' => true,
  ],
  ...
}

Thank you in advance!

doncadavona
  • 7,162
  • 9
  • 41
  • 54

1 Answers1

2

Unfortunately, Backpack cannot make a model_function column orderable, since model functions are called after the SQL has already gotten back.

Sorry.

tabacitu
  • 6,047
  • 1
  • 23
  • 37
  • Okey. Thanks. I got it resolved thou, with additional column (balance) in my database table (users). So that it is directly sortable. But requires additional database storage and processing just to make an attribute sortable in the Datatable. – doncadavona Aug 29 '18 at 23:44
  • @abacitu So then how to order type model_function or closure in backpack? – Senthurkumaran Apr 07 '20 at 05:03