合并两个OR子句而非AND的Laravel Builder约束

时间:2018-10-26 14:49:10

标签: sql laravel builder

我所拥有的: 1.具有方法$this->forTeam()的存储库,该方法用于范围查询以选择团队数据。返回Eloquent \ Builder:

/**
 * Retrieve Unit Activities for specific team + all Unit Activities for Units that belong to Team
 *
 * @param Team $team
 * @return mixed
 */
public function forTeam(Team $team)
{
    $unitsIds      = $team->units()->pluck('id')->toArray();
    $unitGroupsIds = $team->unitGroups()->pluck('id')->toArray();

    return \App\UnitActivity::where(function ($query) use ($unitsIds, $team, $unitGroupsIds) {
        $query->where(function ($query) use ($unitsIds) {
            $query->where('executable_type', Unit::class)
                ->whereIn('executable_id', $unitsIds);
        })->orWhere(function ($query) use ($team) {
            $query->where('executable_type', Team::class)
                ->where('executable_id', $team->id);
        })->orWhere(function ($query) use ($unitGroupsIds) {
            $query->where('executable_type', UnitGroups::class)
                ->whereIn('executable_id', $unitGroupsIds);
        });
    });
}

2。我在上述存储库中的新方法,在该方法中,我尝试重用$this->forTeam()来保持DRY:

/**
 * Retrieve Unit Activities for multiple teams + all Unit Activities for Units that belong to Team
 *
 * @param Team $team
 * @return mixed
 */
public function forTeams(Collection $teams): Builder
{
    $builder = \App\UnitActivity::query();

    $teams->each(function ($team) use (&$builder) {
        $builder = $builder->mergeConstraintsFrom($this->forTeam($team));
    });

    return $builder;
}
  1. 因此,laravel将这两个查询与AND子句合并。

问题是: 如何将这两个查询与OR子句合并? 屏幕上分别附加了$builder->toSql()$builder->getBindings()

enter image description here

0 个答案:

没有答案