Anas Alpure
Anas Alpure

Reputation: 520

many-to-many relationship OrderBy - Laravel query builder

enter image description here

I am trying to order products by thp price in options table the price can be in multi currency for that i add dolor_price calculated as code below. but the result was the following Error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'options.dolor_price' in 'order clause'

    $products=Product::with(["options"=> function($option){
        $option->where('name' ,'unique name' );

        $option->selectSub(function ($q) {
            $rateEruToDolor =2;
            $rateAedToDolor =3;
            $q->selectRaw(' IF(currency=0,price * ?, IF(currency=1,price * ?, price))',
            [$rateEruToDolor,$rateAedToDolor]);
        }, 'dolor_price');
    }]);
    $products->orderBy('options.dolor_price');
    dd($products->get()->toArray());

Upvotes: 1

Views: 157

Answers (1)

Oludotun
Oludotun

Reputation: 107

Try this:

$rateEruToDolor =2;
$rateAedToDolor =3;
$products = Product::join('product_options', 'products.id', '=', 'product_options.product_id')
      ->join('options', 'product_options.option_id', '=', 'options.id')
      ->selectRaw('price, currency, IF(currency=0, price * ?, IF(currency=1, price * ?, price)) 
                   as dolor_price', [$rateEruToDolor, $rateAedToDolor]);
$products->orderBy('dolor_price');
dd($products->get()->toArray());

List all of the fields in your products/options table along with price and currency already listed in the selectRaw('xxx, xxx, price, currency, IF ...) method above. Hope this helps

Upvotes: 1

Related Questions