iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
1
Software Development

從零開始的Laravel RESTful api系列 第 23

Day 23 : 貼文 ( Controller -- index & show ) [ eager loading ]

接下來這一篇就來實作 index 和 show,並且過程中也會提到關聯性的一些小技巧

  • index

    *PostsController

    namespace App\Http\Controllers;vv
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use App\Post;
    
    class PostsController extends Controller
    {
        public function index()
        {
            return response(['data' => Post::get()]);
        }
    }
    

    然而,若要連該貼文所屬的使用者所有資料( 當然不含 hidden attribute )一起印出來呢??我們可以用以下寫法:

    Post::with('user')->get()
    

    甚至可以限定印出的使用者只要某幾個欄位

    Post::with('user:id,name')
    
  • show

    show method 的原理其實也跟之前 user 的部份雷同,此處就不再贅述,並且同樣的可以應用 eager loading 的方式

    *PostsController

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use App\Post;
    
    class PostsController extends Controller
    {
        public function show($id)
        {
            // 找尋該筆資料,連同 user 的部份一起印出
            $post = Post::with('user')->find($id);
    
            if(!is_null($post)){
                return response(['data' => $post]);
            }
    
            return response(['message' => 'Post not found']);
        }
    }
    

Postman 實測

  • index

    • 一般取法

      image alt

    • eager loading ( user 的所有欄位 )

      image alt

    • eager loading ( user 的部份欄位 )

      image alt

  • show

    • 找不到貼文

      image alt

    • 取得某篇貼文 ( 含 user 的資料 )

      image alt

參考資料:

  1. Eager loading : https://laravel.com/docs/6.x/eloquent-relationships#eager-loading

上一篇
Day 22 : 貼文 ( Controller -- store )
下一篇
Day 24 : 貼文 ( controller -- userPosts ) [ eloquent relationship method ]
系列文
從零開始的Laravel RESTful api30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言