/** * Add the constraints for a relationship count query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parent * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationCountQueryForSelfRelation(Builder $query, Builder $parent) { $query->select(new Expression('count(*)')); $query->from($query->getModel()->getTable() . ' as ' . ($hash = $this->getRelationCountHash())); $query->getModel()->setTable($hash); $key = $this->wrap($this->getQualifiedParentKeyName()); return $query->where($hash . '.' . $this->getPlainForeignKey(), '=', new Expression($key)); }
/** * Applies criterion to query. * * @param Builder $builder query builder */ public function apply(Builder $builder) { $sortMethod = 'sort' . studly_case($this->getField()); if (method_exists($builder->getModel(), $sortMethod)) { call_user_func_array([$builder->getModel(), $sortMethod], [$builder, $this->getOrder()]); } else { $builder->orderBy($this->getField(), $this->getOrder()); } }
/** * @return array list of relations that can be eagerly loaded */ protected function _getWithableRelations(Builder $builder) { if (method_exists($builder->getModel(), 'getWithableRelations')) { return $builder->getModel()->getWithableRelations(); } if (property_exists($builder->getModel(), 'withable')) { return $builder->getModel()->withable; } throw new RuntimeException(sprintf('Model %s must either implement getWithableRelations() or have $withable property set', get_class($builder->getModel()))); }
/** * @param Builder $builder * * @return array list of sortable attributes */ protected function _getSortableAttributes(Builder $builder) { if (method_exists($builder->getModel(), 'getSortableAttributes')) { return $builder->getModel()->getSortableAttributes(); } if (property_exists($builder->getModel(), 'sortable')) { return $builder->getModel()->sortable; } throw new RuntimeException(sprintf('Model %s must either implement getSortableAttributes() or have $sortable property set', get_class($builder->getModel()))); }
/** * Initialize * * @return void */ public function initialize() { if (!$this->initialized) { $query = $this->builder->toBase(); $sql = $query->toSql(); $bindings = $query->getBindings(); $conn = $query->getConnection(); $this->statement = $conn->getPdo()->prepare($sql); $this->statement->execute($conn->prepareBindings($bindings)); $this->prototype = $this->builder->getModel()->newFromBuilder(); } $this->initialized = true; }
/** * @param Model|Builder $model * @return Model */ public function search($model) { if ($model instanceof SearchableModel) { $this->fieldConfig = $model->searchableFields(); $this->primaryTable = $model->getTable(); } if ($model instanceof Relation) { $this->primaryTable = $model->getModel()->getTable(); $this->fieldConfig = $model->getModel()->searchableFields(); $this->apply($model->getQuery()); return $model; } return $this->apply($model); }
/** * @param Builder $query */ private function getOrderColumn($query) { if ($this->column instanceof Expression) { return $this->column; } return $query->getModel()->getTable() . '.' . $this->column; }
/** * If column name could not be resolved then use primary key. * * @return string */ protected function getPrimaryKeyName() { if ($this->isEloquent()) { return $this->query->getModel()->getKeyName(); } return 'id'; }
/** * Applies filter to given query * * @param Builder $queryBuilder */ public function apply(Builder $queryBuilder) { if ($this->value()) { $related = $this->list->getCallable($queryBuilder->getModel(), $this->field, false); $queryBuilder->where($this->qualifiedFieldName($related, $related->getKeyName()), $this->value()); } }
/** * Create a new morph to many relationship instance. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $parent * @param string $name * @param string $table * @param string $foreignKey * @param string $otherKey * @param string $relationName * @param bool $inverse * @return void */ public function __construct(Builder $query, Model $parent, $name, $table, $foreignKey, $otherKey, $relationName = null, $inverse = false) { $this->inverse = $inverse; $this->morphType = $name . '_type'; $this->morphClass = $inverse ? $query->getModel()->getMorphClass() : $parent->getMorphClass(); parent::__construct($query, $parent, $table, $foreignKey, $otherKey, $relationName); }
public function generateFromRelations() { $this->parent = $this->query->getModel(); foreach (explode('.', $this->relations) as $index => $relation) { $this->index = $index; $this->relation = call_user_func(array($this->parent, $relation)); $this->related = $this->relation->getRelated(); if ($this->nested) { if (!array_key_exists($this->index, $this->ons)) { $this->ons[$this->index] = []; } if (!array_key_exists($this->index, $this->conditions)) { $this->conditions[$this->index] = []; } } if ($this->relation instanceof BelongsTo) { $this->generateJoinFromBelongsTo($this->relation); } elseif ($this->relation instanceof BelongsToMany) { $this->generateJoinFromBelongsToMany($this->relation); } elseif ($this->relation instanceof HasOneOrMany) { $this->generateJoinFromHasOneOrMany($this->relation); } $this->parent = $this->relation->getRelated(); } if ($this->addNullCondition) { if ($this->relation instanceof BelongsTo) { $this->generateNullConditionFromBelongsTo($this->relation); } elseif ($this->relation instanceof BelongsToMany) { $this->generateNullConditionFromBelongsToMany(); } elseif ($this->relation instanceof HasOneOrMany) { $this->generateNullConditionFromHasOneOrMany($this->relation); } } }
/** * Create a new relation instance. * * @param Illuminate\Database\Eloquent\Builder * @param Illuminate\Database\Eloquent\Model * @return void */ public function __construct(Builder $query, Model $parent) { $this->query = $query; $this->parent = $parent; $this->related = $query->getModel(); $this->addConstraints(); }
/** * @param Builder $builder * @param Model $model */ public function apply(Builder $builder, Model $model) { if (!Auth::guest() && Auth::user()->hasCountryRole()) { $country = Auth::user()->country; if ($builder->getModel()->getTable() == "activity_logs") { $builder->whereHas('contract', function ($q) use($country) { $q->whereRaw("contracts.metadata->'country'->>'code' in (?)", $country); }); } elseif ($builder->getModel()->getTable() == "contract_annotations") { $builder->whereHas('contract', function ($q) use($country) { $q->whereRaw("contracts.metadata->'country'->>'code' in (?)", $country); }); } else { $builder->whereRaw("contracts.metadata->'country'->>'code' in (?)", $country); } } }
/** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function addOnlyOffline(Builder $builder) { $builder->macro('onlyOffline', function (Builder $builder) { $model = $builder->getModel(); $builder->withoutGlobalScope($this)->where($model->getQualifiedStatusColumn(), '=', false); return $builder; }); }
/** * @param Builder $builder */ protected function addOnlyOldVersions(Builder $builder) { $builder->macro('onlyOldVersions', function (Builder $builder) { $model = $builder->getModel(); $builder->withoutGlobalScope($this)->where($model->getQualifiedIsCurrentVersionColumn(), 0); return $builder; }); }
/** * Create new joiner instance. * * @param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder $query * @param \Illuminate\Database\Eloquent\Model $model * @return \Sofa\Eloquence\Relations\Joiner */ public static function make($query, Model $model = null) { if ($query instanceof EloquentBuilder) { $model = $query->getModel(); $query = $query->getQuery(); } return new Joiner($query, $model); }
/** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function addOnlyTrashed(Builder $builder) { $builder->macro('onlyTrashed', function (Builder $builder) { $model = $builder->getModel(); $this->remove($builder, $model); $builder->getQuery()->where($model->getQualifiedDeletedAtColumn(), 'trash'); return $builder; }); }
protected function addOnlyArchived(Builder $builder) { $builder->macro('onlyArchived', function (Builder $builder) { $model = $builder->getModel(); $this->remove($builder, $model); $builder->getQuery()->whereNotNull($model->getQualifiedArchivedAtColumn()); return $builder; }); }
public function excludeCriterion(QueryBuilder $query, $columns) { $columns = static::getArgumentsArray($columns, func_get_args()); // Get the attributes of the model and filter out all but specified $schema = $query->getQuery()->getConnection()->getSchemaBuilder(); $allColumns = $schema->getColumnListing($query->getModel()->getTable()); $difference = array_diff($allColumns, $columns); return $query->select($difference); }
/** * Return a model (or collection of models) for given query or throw an exception. * * @param \Illuminate\Database\Eloquent\Builder $query * @param int $expectedNoElements * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function findByQueryOrFail($query, $expectedNoElements = 1) { $result = $query->get(); $noElements = count($result); if ($noElements and ($noElements === $expectedNoElements or !is_int($expectedNoElements))) { return $result; } throw (new ModelNotFoundException())->setModel(get_class($query->getModel())); }
/** * @param Builder $builder */ protected function addOnlyOldVersions(Builder $builder) { $builder->macro('onlyOldVersions', function (Builder $builder) { $model = $builder->getModel(); $this->remove($builder, $model); $builder->getQuery()->where($model->getQualifiedIsCurrentVersionColumn(), 0); return $builder; }); }
/** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * * @return void */ protected function addOnlyDrafts(Builder $builder) { $builder->macro('onlyDrafts', function (Builder $builder) { $model = $builder->getModel(); $this->remove($builder, $model); $builder->getQuery()->where($model->getQualifiedDraftColumn(), 0); return $builder; }); }
/** * Add the allVersions extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ protected function addAllVersions(Builder $builder) { $builder->macro('allVersions', function (Builder $builder) { $model = $builder->getModel(); $this->remove($builder, $builder->getModel()); $builder->join($model->getVersionTable(), function ($join) use($model) { $join->on($model->getQualifiedKeyName(), '=', $model->getQualifiedVersionKeyName()); }); return $builder; }); }
/** * Remove the scope from the given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return void */ public function remove(Builder $builder) { $column = $builder->getModel()->getQualifiedActivatedAtColumn(); $query = $builder->getQuery(); foreach ((array) $query->wheres as $key => $where) { if ($this->isActivatedConstraint($where, $column)) { unset($query->wheres[$key]); $query->wheres = array_values($query->wheres); } } }
/** * Join the default join tables * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model|null $model * @return void */ public function apply(Builder $builder, EloquentModel $model = null) { // Laravel 4.x doesn't provide the model as an argument if (is_null($model)) { $model = $builder->getModel(); } foreach ($model->defaultJoinTables() as $table) { $model->requireTable($builder, $table); $this->joins[] = end($builder->getQuery()->joins); } }
/** * Remove the original where clause set by the relationship. * * The remaining constraints on the query will be reset and returned. * * @return array */ public function getAndResetWheres() { // When a model is "soft deleting", the "deleted at" where clause will be the // first where clause on the relationship query, so we will actually clear // the second where clause as that is the lazy loading relations clause. if ($this->query->getModel()->isSoftDeleting()) { $this->removeSecondWhereClause(); } else { $this->removeFirstWhereClause(); } return $this->getBaseQuery()->getAndResetWheres(); }
/** * Remove the scope from the given Eloquent query builder. * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function remove(BuilderBase $builder, ModelBase $model) { $column = $builder->getModel()->getLeftColumnName(); $query = $builder->getQuery(); foreach ((array) $query->orders as $key => $order) { if (!$this->isNestedTreeConstraint($order, $column)) { continue; } unset($query->orders[$key]); $query->orders = array_values($query->orders) ?: null; } }
/** * @param EloquentBuilder $query * @param EloquentBuilder $parent * @param array $columns * * @return mixed */ public function getRelationQuery(EloquentBuilder $query, EloquentBuilder $parent, $columns = ['*']) { $query->select($columns); $table = $query->getModel()->getTable(); $query->from($table . ' as ' . ($hash = $this->getRelationCountHash())); $grammar = $query->getQuery()->getGrammar(); $table = $grammar->wrapTable($table); $hash = $grammar->wrapTable($hash); $lft = $grammar->wrap($this->parent->getLftName()); $rgt = $grammar->wrap($this->parent->getRgtName()); return $query->whereRaw("{$hash}.{$lft} between {$table}.{$lft} + 1 and {$table}.{$rgt}"); }
public function remove(Builder $builder) { $model = $builder->getModel(); $column = $model->getQualifiedStatusColumn(); $query = $builder->getQuery(); $bindingKey = 0; foreach ((array) $query->wheres as $key => $where) { if ($this->isStatusConstraint($where, $column)) { $this->removeWhere($query, $key); $this->removeBinding($query, $bindingKey); } if (!in_array($where['type'], ['Null', 'NotNull'])) { $bindingKey++; } } }
/** * Counts current query * * @param string $count variable to store to 'count_all' for iTotalRecords, 'display_all' for iTotalDisplayRecords * * @return null */ protected function count($count = 'count_all') { //Get columns to temp var. if ($this->query_type == 'eloquent') { $query = $this->query->getQuery(); $connection = $this->query->getModel()->getConnection()->getName(); } else { $query = $this->query; $connection = $query->getConnection()->getName(); } // if its a normal query ( no union ) replace the select with static text to improve performance $countQuery = clone $query; if (!preg_match('/UNION/i', $countQuery->toSql())) { $countQuery->select(DB::raw("'1' as row")); // if query has "having" clause add select columns if ($countQuery->havings) { foreach ($countQuery->havings as $having) { if (isset($having['column'])) { $countQuery->addSelect($having['column']); } else { // search filter_columns for query string to get column name from an array key $found = false; foreach ($this->filter_columns as $column => $filter) { if ($filter['parameters'][0] == $having['sql']) { $found = $column; break; } } // then correct it if it's an alias and add to columns if ($found !== false) { foreach ($this->columns as $col) { $arr = preg_split('/ as /i', $col); if (isset($arr[1]) && $arr[1] == $found) { $found = $arr[0]; break; } } $countQuery->addSelect($found); } } } } } // Clear the orders, since they are not relevant for count $countQuery->orders = null; $this->{$count} = DB::connection($connection)->table(DB::raw('(' . $countQuery->toSql() . ') AS count_row_table'))->setBindings($countQuery->getBindings())->count(); }