1

我正在尝试创建一个匹配系统。找到匹配项后,我想向找到匹配项的用户广播。我想不通 - 我应该改用轮询吗?

我的 User 模型与 Match 模型有 belongsToMany 关系。

这是我的代码不起作用。

路线:

Broadcast::channel('match.{matchId}', function ($user, $matchId) {
    return $user->matches()->contains('id', $matchId);
});

零件:

class PlayComponent extends Component
{
    public $matchId;

    public function getListeners()
    {
        return [
            "echo-private:match.{$this->matchId},JoinMatch" => 'joinMatch',
        ];
    }

    public function render()
    {
        return view('livewire.play-component', [
            'matches' => Auth::user()->matches()->get()->toArray(),
        ]);
    }

    public function play()
    {
        if ($match = Match::where('status', 'waiting')->first()) {
            $this->matchId = $match->id;
            event(new JoinMatch($match));
        }
        else {
            $this->matchId = Auth::user()->matches()->create(['status' => 'waiting']);
        }
    }

    public function joinMatch()
    {
        // ???
    }
}

看法:

<div>
    <button class="btn btn-success" wire:click="play">Play</button>
    <hr>
    <pre>{{ print_r($matches, true) }}</pre>
</div>

事件:

class JoinMatch implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $match;

    public function __construct(Match $match)
    {
        $this->match = $match;
        $this->match->users()->attach(Auth::user()->id);
    }

    public function broadcastOn()
    {
        return new PrivateChannel('match.' . $this->match->id);
    }
}

我该如何进行这项工作?我认为问题出在getListeners需要一个参数,但匹配的用户可能还不存在这个参数。

4

0 回答 0