在 Laravel 中,根据用户 ID 获取推荐用户通常涉及到数据库查询和可能的业务逻辑。以下是一个基本的示例,说明如何实现这一功能。
假设我们有一个 User
模型,并且用户之间通过一个中间表 follows
表示关注关系。我们需要根据某个用户的 ID 获取其推荐用户。
users
表:存储用户信息。follows
表:存储用户之间的关注关系,包含 follower_id
和 followee_id
字段。class User extends Model
{
public function followers()
{
return $this->belongsToMany(User::class, 'follows', 'followee_id', 'follower_id');
}
public function followees()
{
return $this->belongsToMany(User::class, 'follows', 'follower_id', 'followee_id');
}
}
use App\Models\User;
function getRecommendedUsers($userId)
{
$user = User::find($userId);
if (!$user) {
return [];
}
// 获取当前用户的关注者
$followers = $user->followers;
// 获取当前用户关注的人
$followees = $user->followees;
// 基于共同关注者推荐用户
$recommendedUsers = User::whereNotIn('id', [$userId])
->whereIn('id', function ($query) use ($followers) {
$query->select('followee_id')
->from('follows')
->whereIn('follower_id', $followers->pluck('id')->toArray())
->groupBy('followee_id')
->havingRaw('COUNT(DISTINCT follower_id) > 1');
})
->get();
return $recommendedUsers;
}
通过上述方法,可以在 Laravel 中有效地根据用户 ID 获取推荐用户,并处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云