【问题标题】:Laravel event attendees eloquent vs collectionsLaravel 活动参与者雄辩 vs 收藏
【发布时间】:2020-10-11 15:57:09
【问题描述】:

我有一种情况,用户可以从一系列活动日期中选择一个,但仅限于当前参加者人数不超过每个活动可用空间的设定数量的活动。

架构

        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 查询中完成集合上的 filter() 位?

【问题讨论】:

    标签: laravel collections eloquent


    【解决方案1】:

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

    $availableEvents = Event::query()
        ->whereRaw('spaces_available - (select count(*) from users where event_id = events.id) > 0')
        ->get();
    

    当然,您可以为此添加一个范围到您的 Event 模型中:

    class Event extends Model
    {
        public function attendees()
        {
            return $this->hasMany(User::class);
        }
    
        public function scopeStillAvailable($query)
        {
            $query->whereRaw('spaces_available - (select count(*) from users where event_id = events.id) > 0');
        }
    }
    

    现在你可以这样做了:

    $availableEvents = Event::stillAvailable()->get();
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      相关资源
      最近更新 更多