Laravel 5.7-“ orderBy”未排序结果

时间:2018-11-27 16:45:11

标签: php laravel eloquent sql-order-by

  1. 我有三种通过hasMany关系关联的模型:Course / Lesson / Article-一个Course hasMany Lessons其中hasMany {{1 }}。

  2. 我的Articles表中有一个int列,名为articles(位置的缩写),我想以此来订购文章。

  3. 我在pos中使用以下查询,但未通过此CoursesController属性对文章进行排序:

    公共功能展示(课程$课程,课程$课程,文章$ articles)         {             $ articles = $ lesson-> articles()-> orderBy('pos','asc')-> get();             返回视图('users.courses.show',紧凑型('course','课程',             “文章”));         }

我正在刀片中使用foreach循环:

pos

任何帮助将不胜感激!

Laravel调试栏显示以下结果:

  

@foreach($lesson->articles as $article) {{ $article->title }} @endforeach 中选择*,其中articles ='this-is-article-one'limit 1       13.27ms \ vendor \ laravel \ framework \ src \ Illuminate \ Routing \ ImplicitRouteBinding.php:35

     

slug中选择*,其中articles = 1并且lesson_id <2由pos排序desc限制1660μs\ app \ Http \ Controllers \ Users \ ArticlesController.php :55

     

pos中选择*,其中articles = 1且lesson_id> 2由pos排序asc限制1520μs\ app \ Http \ Controllers \ Users \ ArticlesController.php :59

     

pos中选择*,其中coursescourses = 2个极限1,610μsview :: users.articles.show:7

     

id中选择*,其中lessonslessons = 1个极限1530μs       view :: users.articles.show:8

     

id中选择*,其中articlesarticles = 1且lesson_idarticles不为空

3 个答案:

答案 0 :(得分:0)

在显示视图中再次调用$lesson->articles时,基本上就是进行新的数据库调用。要获取正确的值,请使用变量$articles

@foreach($articles as $article)
   {{ $article->title }}
@endforeach

答案 1 :(得分:0)

如果您想继续使用视图中的lesson对象,请使用sortBy

@foreach($lesson->articles->sortBy('pos') as $article)
   {{ $article->title }}
@endforeach

答案 2 :(得分:0)

我建议您与orderBy()扩大关系

"dependencies": {
    "@angular/animations": "8.0.0",
    "@angular/common": "8.0.0",
    "@angular/compiler": "8.0.0",
    "@angular/core": "8.0.0",
    "@angular/forms": "8.0.0",
    "@angular/http": "8.0.0-beta.10",
    "@angular/platform-browser": "8.0.0",
    "@angular/platform-browser-dynamic": "8.0.0",
    "@angular/router": "8.0.0",
    "font-awesome": "^4.7.0",
    "nativescript-accordion": "^6.0.0-beta.2",
    "nativescript-angular": "8.0.2",
    "nativescript-checkbox": "^3.0.3",
    "nativescript-drop-down": "^4.0.1",
    "nativescript-feedback": "^1.3.9",
    "nativescript-geolocation": "5.1.0",
    "nativescript-iqkeyboardmanager": "^1.3.0",
    "nativescript-loading-indicator": "^2.4.0",
    "nativescript-ng-ripple": "^2.0.1",
    "nativescript-phone": "^1.4.0",
    "nativescript-plugin-firebase": "9.0.2",
    "nativescript-ratings": "^1.0.1",
    "nativescript-theme-core": "~1.0.4",
    "nativescript-ui-listview": "7.0.0",
    "reflect-metadata": "~0.1.10",
    "rxjs": "~6.4.0",
    "tns-core-modules": "^6.1.1",
    "zone.js": "0.9.1"
  },
  "devDependencies": {
    "@angular/compiler-cli": "8.2.0",
    "@nativescript/schematics": "~0.4.0",
    "@ngtools/webpack": "8.2.0",
    "nativescript-dev-webpack": "^1.2.0",
    "tns-platform-declarations": "6.0.1",
    "typescript": "3.4.5"
  }
```