首页 > 解决方案 > Laravel mysql查询返回通知

问题描述

$groups = DB::table('user_hobbies')
    ->where('user_id', '==', $user->id)
    ->leftJoin('hobbies', 'hobbies.id', '=', 'user_hobbies.hobby_id')
    ->where('hobbies.admin_id', '!=', $user->id)
    ->select('hobbies.*')
    ->orderBy('name', 'ASC')
    ->get();

if ($groups->count() > 0) {
    foreach ($groups as $group){
        $name = DB::table('user_hobbies')
            ->where('id', $group->admin_id)
            ->value('first_name');
 
        $avatar = DB::table('user_hobbies')
            ->where('id', $group->admin_id)
            ->value('avatar_location');

        $notifications[] = [
            'url' => url('/groups/'),
            'icon' => 'fas fa-comment',
            'text' => $name.' added you to a new group!',
            'img' => url('/storage/'.$avatar)
        ];
    }
}

嘿伙计们,这里的初学者.. 我正在尝试添加一个通知,以便管理员将用户添加到新组时,我正在使用此代码尝试返回通知,但通知中没有出现任何内容,它是空的。有错误吗?我似乎不太理解这个问题,因为我正在遵循一个类似的功能,该功能在返回评论通知时确实有效。知道我哪里出错了或者接下来应该看哪里吗?

标签: mysqllaravel

解决方案


您可以获得所需的结果(至少在$notifications具有单个查询的数组中。

根据我掌握的少量信息,这应该可行。

$groups = DB::table('user_hobbies')
    ->select('first_name', 'avatar_location')
    ->whereIn('id', function ($sub) use ($user) {
        return $sub->select('hobbies.admin_id')
            ->from('user_hobbies')
            ->leftJoin('hobbies', 'hobbies.id', 'user_hobbies.hobby_id')
            ->where('user_id', $user->id)            
            ->where('hobbies.admin_id', '!=', $user->id);
    })
    ->get();

$notifications = $groups->map(function ($group) {
    return [
        'url' => url('/groups/'),
        'icon' => 'fas fa-comment',
        'text' => $group->first_name.' added you to a new group!',
        'img' => url('/storage/'.$group->avatar_location)
    ];
})
->all();

推荐阅读