0

我试图在第二个用户在游戏中出价后向在游戏中第一个出价的用户发送通知。

我有表格 game_bids,其中有 id、user_id 和 game_id。我试图从表中找到与当前打开的游戏相同的 game_id。

我不擅长 laravel,无法弄清楚如何让它正常工作。我需要 $user = 的帮助(我将通过它来通知)。

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Game_bid;
use App\Game;
use Auth;
use Illuminate\Support\Facades\Lang;
use DB;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Notification;
use App\Notifications\GameBiddedNotification;


class PointsController extends Controller {
public function bid($game_id) {
        $bid = new Game_bid;
        $bid->game_id = $game_id;
        $bid->user_id = Auth::user()->id;
        $bid->is_awarded = 0;

        if ($bid->save()) {
            $game = Game::find($game_id);
            $user = User::find(Auth::user()->id);
            $user->points = $user->points - $game->points;
            $user->save();
        }

        **$user = Game_bid::where('user_id')
                ->where('game_id', Game::find($game_id))
                ->first();**

        $details = [
                'greeting' => $game->title,
                'body' => '.',
                'thanks' => '!',
        ];

        $user->notify(new \App\Notifications\GameBiddedNotification($details));

        return redirect('my_bids')->with('success', 'Your bid placed successfully');
    }
4

1 回答 1

1

如果我理解正确,可能会有多个用户需要通知(每个对这款游戏出价的人)。因此,要检索并通知所有其他对该游戏出价的用户,您可以执行以下操作:

public function bid($game_id) {
    $bid = new Game_bid;
    $bid->game_id = $game_id;
    $bid->user_id = Auth::user()->id;
    $bid->is_awarded = 0;

    if ($bid->save()) {
        $game = Game::find($game_id);
        $user = User::find(Auth::user()->id);
        $user->points = $user->points - $game->points;
        $user->save();
    }

    $users = User::whereHas('game_bids', function ($query) use ($game_id, $bid) {
        $query->where('game_id', $game_id)->where('user_id', '!=', $bid->user_id);
    })->get();

    $details = [
        'greeting' => $game->title,
        'body' => '.',
        'thanks' => '!',
    ];

    foreach ($users as $user) {
        $user->notify(new \App\Notifications\GameBiddedNotification($details));
    }

    return redirect('my_bids')->with('success', 'Your bid placed successfully');
}
于 2020-04-12T17:17:51.347 回答