Laravel default orderBy

后端 未结 8 1800
离开以前
离开以前 2020-12-24 10:51

Is there a clean way to enable certain models to be ordered by a property by default? It could work by extending the laravel\'s QueryBuilder, but to do so,

8条回答
  •  太阳男子
    2020-12-24 11:34

    you should use eloquent global scope that can apply to all queries(also you can set parameter for it).

    And for relations you can use this useful trick:

    class Category extends Model {
        public function posts(){
            return $this->hasMany('App\Models\Post')->orderBy('title');
        }
    }
    

    this will add order by to all posts when we get them from a category. If you add an order by to your query, this default order by will cancel!

提交回复
热议问题