0

I have this method in a Model called Category, that brings all products from certain Category.

Model:

public function products()
{
    return $this->hasMany(Product::class);
}

What I would like is put these products in order based on Array with IDs.

I tried this but didn't work:

public function products()
{
    if ( !is_null($this->products_order)) {
        $order = json_decode($this->products_order, true);

        $products = $this->hasMany(Product::class)->orderBy('id',...$order);
        return $products;
    }

    return $this->hasMany(Product::class);
}

$this->products_order is a Array of IDs.

Ahmad Karimi
  • 1,285
  • 2
  • 15
  • 26
  • 1
    MySQL has a order by field, but other relational database don't afaik, so I wouldn't expect eloquent to support this since eloquent tries to be database agnostic. If you don't case about coupling to mysql, you can look at https://stackoverflow.com/questions/9378613/how-to-define-a-custom-order-by-order-in-mysql with a raw statement. – Devon Bessemer Feb 13 '19 at 01:51
  • 1
    Instead of using column with arrays of ID, why dont you just create pivot table? – Adlan Arif Zakaria Feb 13 '19 at 01:54
  • Thanks, guys. I changed my approach, I create a new field for product table called order, and I'ts work better. – Vinicius Cainelli Feb 13 '19 at 03:57

0 Answers0