#laravel #model #laravel-8 #mutual-friendship
Вопрос:
Я использую laravel 8. Я хочу найти общих друзей по записям и профилям.
Пожалуйста, спросите меня, не ясно ли это…
Стол моих друзей;
user_friends;
id | user_id | user_friend_id
1 | 10 | 20
2 | 20 | 10
В Моей Пользовательской Модели;
public function friends(){
return $this->belongsToMany(User::class, 'user_friends', 'user_id', 'user_friend_id');
}
public function friendsOf(){
return $this->belongsToMany(User::class, 'user_friends', 'user_friend_id', 'user_id');
}
Как я могу найти общих друзей профиля в отношении аутентифицированного пользователя?
Пример;
@foreach($user as $entry)
{{ count( $entry->mutual(Auth::id()) ) }}
@foreach($entry->mutual(Auth::id()) as $item)
{{ $item->name }}
...
@endforeach
@endforeach
Ответ №1:
Я делаю эту работу с помощью помощников. Я создаю helpers.php в папке приложения и создайте функцию.
function mutualFriends($id){
$profile = User::where('id', $id)->first();
$profileFriends = $profile->friends;
$profileFriendsIds = [];
foreach ($profileFriends as $entry){
$profileFriendsIds[] = $entry->id;
}
$loggedUserFriends = Auth::user()->friends->whereIn('id', $profileFriendsIds);
return $loggedUserFriends;
}
и теперь я вызываю функцию из вида, как;
{{count(mutualFriends(Auth::id()))}}
или
@foreach(mutualFriends($profile->id) as $entry)
...
@endforeach