查询以获取 laravel 中的关系数据

Querying to fetch relationship data in laravel

我正在使用特定的标签 ID 获取 post,目前我有以下代码。

public static function getPostByTag($id) {
    return Tag::with('posts')->whereHas('posts', function($q) use(&$id) {
      $q->where('tags.id',$id);
    })->get();
}

到目前为止,我获得的数据运行良好,但现在,我想限制数据。我应该如何限制数据?

我试过以下方法:

public static function getPostByTag($id) {
    return Tag::with('posts')->whereHas('posts', function($q) use(&$id) {
      $q->where('tags.id',$id);
    })->take(5)->get();
}

但是,它似乎不起作用。另外,我想根据最新日期列出我的 post。

您需要通过以下方式进行:

public static function getPostByTag($id){
    return Tag::whereHas('posts', function($q) use(&$id){
        $q->where('tags.id',$id);
    }->with(['posts' => function($q) {
        $q->orderBy('created_at', 'DESC')->take(5);
    }])->get();
}

看来你想通过tag_id获得post,你可以使用Tag::where('id', $id)

如果你想要最新的posts,你可以使用->latest()方法,它会自动按created_at desc排序。

而你想限制posts,你需要在with闭包中限制它:

public static function getPostByTag($id){
    return Tag::where('id', $id)->has('posts')
              ->with(['posts' => function($q) {
                 $q->latest()->limit(5);
              }])->get();
}