我们有个 A 表,大约是百万级数据,与之关联的有个 B 表,大约万级数据。在做关联查询的时候我们自然使用 A::whereHas(‘b’, function(){…}) 。
后来发现了许多慢查询,仔细一看发现,Laravel 的 whereHas 在生成 SQL 的时候会使用 select * from A where exists ( select * from b where … ) 。当我们的左表远远大于右表时,A 表就成了性能瓶颈。
于是就考虑加了个 whereHasIn 的方法,接口参数跟 whereHas 一致,只不过在生成 SQL 的时候会生成 select * from A where A.id in (select id from B)。这样就不需要改什么 SQL 了,只要在调用 A::whereHas() 的地方加两个字符变成 A::whereHasIn() 就搞定了。
在实际中,我们这条查询的耗时从几秒一下降低到了 20 毫秒。
<?php
use Illuminate\Database\Eloquent\Relations;
abstract class AbstractModel
{
/**
* whereHas 的 where in 实现
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param string $relationName
* @param callable $callable
* @return Builder
*
* @throws Exception
*/
public function scopeWhereHasIn($builder, $relationName, callable $callable)
{
$relationNames = explode('.', $relationName);
$nextRelation = implode('.', array_slice($relationNames, 1));
$method = $relationNames[0];
/** @var Relations\BelongsTo|Relations\HasOne $relation */
$relation = Relations\Relation::noConstraints(function () use ($method) {
return $this->$method();
});
/** @var Builder $in */
$in = $relation->getQuery()->whereHasIn($nextRelation, $callable);
if ($relation instanceof Relations\BelongsTo) {
return $builder->whereIn($relation->getForeignKey(), $in->select($relation->getOwnerKey()));
} elseif ($relation instanceof Relations\HasOne) {
return $builder->whereIn($this->getKeyName(), $in->select($relation->getForeignKeyName()));
}
throw new Exception(__METHOD__ . " 不支持 " . get_class($relation));
}
}
也可以将下面这段代码写到 AppServiceProvider 中,这样就不需要修改原有的模型类了,也不需要创建 Model 基类。
use \Illuminate\Database\Query\Builder;
.
.
.
Builder::macro('whereHasIn', function($builder, $relationName, callable $callable)
{
$relationNames = explode('.', $relationName);
$nextRelation = implode('.', array_slice($relationNames, 1));
$method = $relationNames[0];
/** @var Relations\BelongsTo|Relations\HasOne $relation */
$relation = Relations\Relation::noConstraints(function () use ($method) {
return $this->$method();
});
/** @var Builder $in */
$in = $relation->getQuery()->whereHasIn($nextRelation, $callable);
if ($relation instanceof Relations\BelongsTo) {
return $builder->whereIn($relation->getForeignKey(), $in->select($relation->getOwnerKey()));
} elseif ($relation instanceof Relations\HasOne) {
return $builder->whereIn($this->getKeyName(), $in->select($relation->getForeignKeyName()));
}
throw new Exception(__METHOD__ . " 不支持 " . get_class($relation));
});