Laravel查询范围具有动态值

时间:2019-02-13 17:08:45

标签: mysql laravel

我正在努力提出合适的构建器与原始SQL的组合,以解决我的需求。 我有一个设置,允许用户配置X数量的TournamentQuizmasters所需的X数量的Teams。为了提高效率,我需要在MySQL级别进行此计算,因此我可以快速查询所有合格的团队。我还有其他查询范围来确定什么是合格的团队(例如withEnoughPlayers())。

此代码无效,但我认为它传达了我的意图。

// A collection of Teams
class TeamSet extends Model {
    public function scopeWithEnoughQuizmastersBasedOnTeamCount(Builder $q, Tournament $tournament)
    {
        // Pull only the groups that bring enough quizmasters.  The required number
        // of quizmasters is based off of the number of teams they're bringing.
        return $q->whereHas('group', function (Builder $q) use ($tournament) {
                $q->has(
                    'tournamentQuizmasters',
                    '>=',
                    DB::raw('FLOOR(('.$tournament->settings->quizmastersToRequireByTeamCount().' * '.$q->selectRaw('COUNT(*)')->teams()->withEnoughPlayers($tournament)->toSql().') / '.$tournament->settings->teamCountToRequireQuizmastersBy().')')
                );
        });
    }
}

运行此查询,我得到Call to undefined method Illuminate\Database\Eloquent\Builder::teams(),我相信这是因为进行了selectRaw()处理。我也认为我无法真正使用->teams()的方式打电话给我,但是我对于应该如何更改它以获得我想要的结果却视而不见。

如何在利用查询生成器时执行此动态表达式,以便可以利用自己的作用域?

我正在使用Laravel 5.7

模型与关系

class TeamSet {
    public function group() : BelongsTo
    {
        return $this->belongsTo(Group::class);
    }
    public function teams() : HasMany
    {
        return $this->hasMany(Team::class)
    }
}

class Team {
    public function teamSet() : BelongsTo
    {
        return $this->belongsTo(TeamSet::class)
    }
}

class Group {

    public function tournamentQuizmasters() : HasMany
    {
        return $this->hasMany(TournamentQuizmaster::class);
    }

    public function teams() : HasManyThrough
    {
        return $this->hasManyThrough(Team::class, TeamSet::class);
    }
}

class Tournament {
    public function teamSets() : HasMany
    {
        return $this->hasMany(TeamSet::class);
    }

    public function teams() : HasManyThrough
    {
        return $this->hasManyThrough(Team::class, TeamSet::class);
    }
}

class TournamentQuizmaster {
    public function group() : BelongsTo
    {
        return $this->belongsTo(Group::class);
    }

    public function tournament() : BelongsTo
    {
        return $this->belongsTo(Tournament::class);
    }
}

型号说明:

  • TeamSet-代表团队集合的单个实体。这使我们的用户能够将同一组团队用于多个锦标赛。
  • Team-一组玩家
  • Group-组名。在应用程序的其他位置使用了此功能,但是每个TeamSet都属于一个组。
  • Tournament-十分不言自明
  • TournamentQuizmaster-比赛的裁判或裁判。每个小组需要根据他们的团队人数携带X个

$ tournament->设置

这作为json存储在数据库中,但强制转换为对象,因此我有一个合理的位置来保留默认值。这是该课程的一个片段:

use Illuminate\Support\Fluent;

class Settings extends Fluent
{
    const DEFAULT_MAXIMUM_PLAYERS_PER_TEAM = 5;
    const DEFAULT_MINIMUM_PLAYERS_PER_TEAM = 3;

    public function __construct($attributes = [])
    {
        if ($attributes !== null) {
            parent::__construct($attributes);
        }
    }

    public function shouldRequireQuizmasters() : bool
    {
        return $this->get('requireQuizmasters', 'none') != 'none';
    }

    public function shouldRequireQuizmastersByGroup() : bool
    {
        return $this->get('requireQuizmasters', null) == 'group';
    }

    public function quizmastersToRequireByGroup() : int
    {
        return $this->get('quizmastersToRequireByGroup', 1);
    }

    public function setQuizmastersToRequireByGroup(int $quizmasterCount)
    {
        $this->quizmastersToRequireByGroup = $quizmasterCount;
    }

    public function shouldRequireQuizmastersByTeamCount() : bool
    {
        return $this->get('requireQuizmasters', null) == 'team_count';
    }

    public function quizmastersToRequireByTeamCount() : int
    {
        return $this->get('quizmastersToRequireByTeamCount', 1);
    }

存储在数据库中的json最终看起来像:

{"collectShirtSizes":"1","collectQuizmasterPreferences":"1","allowsGuestPlayers":true,"minimumPlayersPerTeam":3,"maximumPlayersPerTeam":6,"requireQuizmasters":"group","quizmastersToRequireByGroup":1,"quizmastersToRequireByTeamCount":1,"teamCountToRequireQuizmastersBy":2}

1 个答案:

答案 0 :(得分:1)

在下一篇文章中,我已经可以使用subSelect技术完成类似的事情。 https://reinink.ca/articles/dynamic-relationships-in-laravel-using-subqueries

基于此,您可以获取在团队查询中添加了足够玩家的球队数量,并将其与锦标赛测验的大师数量进行比较。希望我对您的查询足够了解。像这样的东西。

/// In Group
public function scopeHasRequiredAmount(Builder $builder, Tournament $tournament)
{
    return $builder->withCount('tournamentQuizmasters')
        ->teamsWithEnoughPlayersCount()
        ->havingRaw(
            'tournamentQuizmasters_count > FLOOR((' . $tournament->settings->quizmastersToRequireByTeamCount() .
            '* teams_with_enough_players_count ) /'
            . $tournament->settings->teamCountToRequireQuizmastersBy() . ')'
        );
}

/// adds count of teams with enough players to query
public function scopeTeamsWithEnoughPlayersCount(Builder $builder, Tournament $tournament)
{
    return $builder->addSubSelect('teams_with_enough_players_count', Team::selectRaw('count(*)')
        ->whereColumn('groups.id', 'teams.group_id')
        ->withEnoughPlayers($tournament)
    );
}

/// In Teamset
function scopeWithEnoughQuizmastersBasedOnTeamCount(Builder $builder, $tournament)
{
    return $builder->whereHas('group', function (Builder $q) use ($tournament) {
        $q->hasRequiredAmount($tournament);
    });

}