使用分页从两个关系一个通过访问器获取记录

问题描述

Laravel 7.x

我需要从两个relations获得帖子。看:

用户有帖子;

用户有好友(访问者);

朋友有帖子;

如何获得所有(用户)自己的帖子以及每个朋友的所有帖子,并分页

哪种方法最好?

仅用于表达我想说的想法:

$user = User::find(1);
$posts = $user->with('posts','friends.posts')->paginate(15); // I wanna get only the Posts collection

解决方法

我建议查询您的Post模型,然后为用户和相关朋友过滤器应用过滤器。

$user = User::with('friends')->find(1);
$userIds = $user->friends->pluck('id')->toArray();
array_push($userIds,$user->id);
$posts = Post::whereIn('user_id',$userIds)->paginate(15);
,

您可以使用 hasManyThrough ,这种关系有点复杂,难以理解提供访问另一模式关系数据的快捷方式。
在您的用户模型中,按以下方式建立关系:

public function posts()
{
   return $this->hasManyThrough(
     Post::class,Friend::class,'user_id',// Foreign key on friends table...
     'friend_id',// Foreign key on posts table...
     'id',// Local key on users table...
     'id' // Local key on friends table...
   );
}

现在您可以像这样从posts模型中获取所有User

$user = User::find(1);
$posts = $user->with('posts')->paginate(15);