首页 > 其他 > 详细

whereHasIn方法

时间:2019-06-19 16:20:18      阅读:219      评论:0      收藏:0      [点我收藏+]

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方法

原文:https://www.cnblogs.com/JdsyJ/p/11051800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!