瀏覽代碼

Use query scopes to get recent comments

Functions can be passed into load() but it looks totally unreadable
axkuhta 1 年之前
父節點
當前提交
cb44cf0dbe
共有 2 個文件被更改,包括 5 次插入1 次删除
  1. 1 1
      app/Http/Controllers/BookController.php
  2. 4 0
      app/Models/Comment.php

+ 1 - 1
app/Http/Controllers/BookController.php

@@ -23,7 +23,7 @@ class BookController extends Controller {
 	}
 
 	function view(Book $book) {
-		return view("book", ["book" => $book->load(["author", "comments"])]);
+		return view("book", ["book" => $book->load(["author" => function($query) {}, "comments" => function($query) { $query->recent(); }])]);
 	}
 
 	function edit(Book $book) {

+ 4 - 0
app/Models/Comment.php

@@ -12,4 +12,8 @@ class Comment extends Model
 		"email",
 		"content"
 	];
+
+	function scopeRecent($query) {
+		$query->orderBy("created_at", "desc");
+	}
 }