在使用laravel7.x 时发布在表子查询时用whereHas 耗时非常大 尝试使用 whereHasIn 替代

1、代码直接放在公共model 层 要使用的model 继承 即可 

/**
     * 添加wherehasin 替代 wherehas 方法
     * @param Builder $builder
     * @param $relationName
     * @param callable $callable
     * @return $this
     * @throws \Exception
     */
    public function scopeWhereHasIn(Builder $builder, $relationName, callable $callable)
    {
        $relationNames = explode('.', $relationName);
        $nextRelation = implode('.', array_slice($relationNames, 1));

        $method = $relationNames[0];
        /** @var Relations\BelongsTo|Relations\HasOne $relation */

        $relation = Relation::noConstraints(function () use ($method) {
            return $this->$method();
        });

        /** @var Builder $in */
        if($nextRelation){
            $in = $relation->getQuery()->whereHasIn($nextRelation, $callable);
        } else {
            $in = $relation->getQuery()->where($callab

版权声明:本文为lemqs0123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。