Laravel distinct在与相关表一起使用时无法正常工作
在Laravel7应用程序中,我有用户表(id,用户名),兴趣(id,名称)和用户兴趣(用户id,兴趣id) 因为任何用户都可能有不同的兴趣。 我需要选择与给定用户有相似兴趣的其他用户。我有:Laravel distinct在与相关表一起使用时无法正常工作,laravel,eloquent,Laravel,Eloquent,在Laravel7应用程序中,我有用户表(id,用户名),兴趣(id,名称)和用户兴趣(用户id,兴趣id) 因为任何用户都可能有不同的兴趣。 我需要选择与给定用户有相似兴趣的其他用户。我有: $userInterests = UserInterest ::getByUserId($user_id) ->with('Interest') ->orderBy('created_at', 'desc') ->get(); // I need give
$userInterests = UserInterest
::getByUserId($user_id)
->with('Interest')
->orderBy('created_at', 'desc')
->get(); // I need given user(user_id) interests
$userInterestIds= [];
foreach( $userInterests as $nextUserInterest ) {
$userInterestIds[]= $nextUserInterest->interest_id;
} // I get interests ID of given user(user_id)
\Log::info( varDump($userInterestIds, ' -1 $userInterestIds::') );
//
$similarUserInterests = UserInterest
::getByInterestId($userInterestIds)
->where(with(new UserInterest)->getTable().'.user_id', '!=', $user_id)
->with('User')
->distinct('user_interests.user_id')
->get();
上面的请求是有效的,但distinct并不像我预期的那样有效。
我看到跟踪(给定用户id=5):
谢谢 我认为以下内容可以满足您的需求
//获取具有给定$user\u id且感兴趣的用户
$user=user::with('interests:id')->findOrFail($user\u id);
//拔出兴趣的ID
$id=$user->interests->pull('id');
//获得其他有类似兴趣的用户
//根据共同兴趣的数量按降序排列
$UserSwithSimilariInterests=用户::withCount('兴趣')
->whereHas('interest',function($query)use($id){
返回$query->其中('id',$id);
})
->orderBy('interests\u count','desc')
->get();
SELECT *
FROM `vfrm_user_interests`
WHERE `vfrm_user_interests`.`user_id` = '5'
ORDER BY `created_at` desc
SELECT *
FROM `vfrm_interests`
WHERE `vfrm_interests`.`id` in (1, 3, 5)
SELECT distinct *
FROM `vfrm_user_interests`
WHERE `vfrm_user_interests`.`interest_id` in ('1', '3', '5') AND `vfrm_user_interests`.`user_id` != '5'
SELECT *
FROM `vfrm_users`
WHERE `vfrm_users`.`id` in (1, 2, 3, 4)