0

拉拉维尔 7.x

我需要从两个relations. 看:

用户有帖子;

用户有好友(访问者);

朋友有帖子;

如何获取所有自己的(用户)帖子和每个朋友的所有帖子,并进行分页?

最好的方法是什么?

只是为了传递我想说的想法:

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

2 回答 2

1

您可以使用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); 
于 2020-08-17T07:55:19.530 回答
1

我建议查询您的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);
于 2020-08-17T05:57:35.457 回答