/** * Add relation based constraints. * * @param Illuminate\Database\Eloquent\Relations\Relation $relation * @param array $args */ public function addDefinedConstraintsToRelation($relation, $args = null) { if ($args === null) { $args = $this->parent->getRelationDefinition($this->relationName); } /* * Pivot data (belongsToMany, morphToMany, morphByMany) */ if ($pivotData = array_get($args, 'pivot')) { $relation->withPivot($pivotData); } /* * Pivot timestamps (belongsToMany, morphToMany, morphByMany) */ if (array_get($args, 'timestamps')) { $relation->withTimestamps(); } /* * Count "helper" relation */ if ($count = array_get($args, 'count')) { if ($relation instanceof BelongsToManyBase) { $relation->countMode = true; } $countSql = $this->parent->getConnection()->raw('count(*) as count'); $relation->select($relation->getForeignKey(), $countSql)->groupBy($relation->getForeignKey()); } }