PostController.php 636 B

12345678910111213141516171819202122232425
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\Post;
  5. class PostController extends Controller
  6. {
  7. public function index()
  8. { //普通查询 n+1
  9. //$posts = Post::orderByDesc('created_at')->paginate(100);
  10. //避免n+1
  11. //$posts = Post::with('author')->orderByDesc('created_at')->paginate(100);
  12. //指定字段 -- 报错了
  13. $posts = Post::with('author:name')
  14. ->select(['id', 'title', 'user_id', 'created_at'])
  15. ->orderByDesc('created_at')
  16. ->paginate(100);
  17. return view('post.index', ['posts' => $posts]);
  18. }
  19. }