我有三种通过hasMany关系关联的模型:Course
/ Lesson
/ Article
-一个Course
hasMany Lessons
其中hasMany {{1 }}。
我的Articles
表中有一个int
列,名为articles
(位置的缩写),我想以此来订购文章。
我在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
中选择*,其中courses
。courses
= 2个极限1,610μsview :: users.articles.show:7从
id
中选择*,其中lessons
。lessons
= 1个极限1530μs view :: users.articles.show:8从
id
中选择*,其中articles
。articles
= 1且lesson_id
。articles
不为空
答案 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"
}
```