I created an appends attribute in Laravel Model, from the code below.
protected $appends = array('total'=>'');
And I set the returned value.
public function getTotalAttribute(){
return ProductPart::where('product_id',$this->id)->count();
}
Then I want to order records from database by using total
attribute
I tried to use Product::orderBy('total','desc')->get()
but it didn't work.
Does anybody has some suggestions to this?
the orderBy takes an actual database field not an appended one
try this
$products = Product::all();
$products = $products->sortBy(function($product){
return $product->total;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With