Laravel Eloquent sort by relation table column

前端 未结 2 700
一生所求
一生所求 2020-11-30 22:59

I tried to sort products from shop_products table by pinned column from shop_products_options table:

$products = Shop\         


        
2条回答
  •  遥遥无期
    2020-11-30 23:25

    You can't sort by related table column without the manually joining related table. Jarek answer is correct but this could be really awkward :

    1.The first problem is that you need to worry about select.

    ->select('products.*')
    

    reason: without select() id from shop_products_options can be selected and hydrated into Product model.

    2.The second problem is that you need to worry about groupBy.

    ->groupBy('products .id');
    

    reason: if the relation is HasOne and there are more than one shop_products_options for the product, the query will return more rows for products.

    3.The third problem is that you need to change all other where clauses from :

    ->where('date', $date)
    

    to

    ->where('products .date', $date)
    

    reason: products and shop_products_options can both have "date" attribute and in that case without selecting attribute with table "ambiguous column" error will be thrown.

    4.The fourth problem is that you are using table names(not models) and this is also bad and awkward.

    ->where('products.date', $date)
    

    5.The fifth problem is that you need to worry about soft deletes for joined tables. If the shop_products_options is using SoftDeletes trait you must add :

    ->where('shop_products_options .deleted_at', '=', null)
    

    All above problems are very frustrating and joining tables with eloquent can introduce to your code many problems. I created a package which takes care of all above problems and you can sort by relationship attribute with elegant way, for your case it would be :

    $products = Shop\Product::orderByJoin('options.pinned', 'desc')->paginate(5);
    

    For more info see https://github.com/fico7489/laravel-eloquent-join

提交回复
热议问题