whereHasIn方法
Posted jdsyj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了whereHasIn方法相关的知识,希望对你有一定的参考价值。
model.php文件\\
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* whereHas 的 where in 实现
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param string $relationName
* @param callable $callable
* @return Builder
*
* @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($callable);
if ($relation instanceof BelongsTo)
return $builder->whereIn($relation->getForeignKey(), $in->select($relation->getOwnerKey()));
elseif ($relation instanceof HasOne)
return $builder->whereIn($this->getKeyName(), $in->select($relation->getForeignKeyName()));
elseif ($relation instanceof HasMany)
return $builder->whereIn($this->getKeyName(), $in->select($relation->getForeignKeyName()));
throw new \Exception(__METHOD__ . " 不支持 " . get_class($relation));
使用 ----- User::where()->whereHasIn(‘goods‘, function($query)
);
以上是关于whereHasIn方法的主要内容,如果未能解决你的问题,请参考以下文章
GroovyGroovy 扩展方法 ( 扩展静态方法示例 | 扩展实例方法示例 | 扩展实例方法与扩展静态方法代码相同 )