many-to-many relationship OrderBy - Laravel query builder

回眸只為那壹抹淺笑 提交于 2021-01-28 08:27:38

问题


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());

回答1:


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



来源:https://stackoverflow.com/questions/61358327/many-to-many-relationship-orderby-laravel-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!