Home > Software engineering >  Sorting in the parent model
Sorting in the parent model

Time:11-27

I have a model in which I am sorting items

public static function getArticleBlocks() {
        return ArticleBlock::orderBy('order', 'ASC')->get();
    }

This model has a parent Article where I output the data with the ArticleBlock data

public static function getArticle($id) {
        return Article::where('id', $id)->with(['blog_categories', 'article_recommendations', 'article_blocks', 'article_comments'])->first();
    }

How can I make the same sorting of article_blocks when get Article?

CodePudding user response:

If you want to sort the hasmany Relation records. You can pass the callback as array value inside with method.

Rename sort_column to your requirement

public static function getArticle($id) 
    {
        return Article::query()
        ->where('id', $id)
                ->with([
                    'blog_categories', 
                    'article_recommendations', 
                    'article_blocks' => function($query){
                    return $query->orderBy('sort_column','ASC');
                    }, 
                    'article_comments'
                ])
                ->first();
    }
  • Related