Laravel活动参与者雄辩与收藏

Laravel活动参与者雄辩与收藏,laravel,collections,eloquent,Laravel,Collections,Eloquent,我的情况是,用户可以从一系列活动日期中选择一个,但只能选择当前参与者数量不超过每个活动可用空间数的活动 模式 Schema::create('events', function (Blueprint $table) { $table->id(); $table->datetime('occurs_at'); $table->smallInteger('spaces_available')-&

我的情况是,用户可以从一系列活动日期中选择一个,但只能选择当前参与者数量不超过每个活动可用空间数的活动

模式

        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->datetime('occurs_at');
            $table->smallInteger('spaces_available')->unsigned()->default('8');
        });
应用程序\事件

    public function attendees ()
    {
        return $this->hasMany(User::class);
    }
查询:

                \App\Event::withCount('attendees')
                    ->get()
                    ->filter(function ($event) {
                        return ($event->spaces_available - $event->attendees_count) > 0;
                    });

只是想知道如何在Eloquent查询中替代集合上的过滤器位?

您可以使用Eloquent中的whereRaw方法手动执行此操作:

$availableEvents=事件::查询 ->whereRaw'spaces\u available-从event\u id=events.id>0的用户中选择count* ->得到; 当然,您可以将此范围添加到事件模型中:

类事件扩展模型 { 公众活动参加者 { 返回$this->hasManyUser::class; } 公共函数作用域仍然可用$query { $query->whereRaw'spaces\u available-从event\u id=events.id>0'的用户中选择count*; } } 现在你可以这样做了:

$availableEvents=Event::stillAvailable->get;