/** * @param \Illuminate\Database\Eloquent\Model $model * @param \anlutro\LaravelValidation\ValidatorInterface $validator */ public function __construct(Model $model, ValidatorInterface $validator = null) { parent::__construct($validator); $this->model = $model; if ($validator) { $validator->replace('table', $this->model->getTable()); } }
/** * Get Record by its ID, with an exception if not found * * @param $id * @return mixed * @throws \App\Core\Repository\EntityNotFoundException */ public function requireById($id) { $model = $this->getById($id); if (!$model) { throw new EntityNotFoundException($id, $this->model->getTable()); } return $model; }
/** * @param Model $model * @param Repository $cache * @param Dispatcher $dispatcher */ public function __construct(Model $model, Repository $cache, Dispatcher $dispatcher) { // DI Member Assignment $this->model = $model; $this->cache = $cache; $this->dispatcher = $dispatcher; // Set the resource name $this->resourceName = $this->model->getTable(); $this->className = get_class($model); }
public function forCompany() { $modelForeignId = $this->model->getTable() . '.' . str_singular($this->throughTableName) . '_id'; $constraint = $this->throughTableName . '.id' . ' = ' . $modelForeignId; return $this->model->whereExists(function ($query) use($modelForeignId, $constraint) { $query->selectRaw(1)->from($this->throughTableName)->where('company_id', '=', $this->companyId)->whereRaw($constraint); if (!is_null($this->throughId)) { $query->where('id', '=', $this->throughId); } }); }
/** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model) { //Check if is an override // $iso = config()->get('local_override'); if (empty($iso)) { $iso = app()->getLocale(); } $builder->whereExists(function ($query) use($model, $iso) { $query->select(\DB::raw(1))->from($model->getQualifiedTable())->whereRaw($model->getTable() . '.' . $model->getKeyName() . ' = ' . $model->getQualifiedIdElementColumn())->where($model->getQualifiedIsoColumn(), $iso)->where($model->getQualifiedModelColumn(), $model->getTable()); }); $this->extend($builder); }
/** * @param Command $command * @param string $modelClass * @param string $title */ function __construct(Command $command, $modelClass, $title) { $this->command = $command; $this->schemaManager = DB::getDoctrineSchemaManager(); $this->schemaManager->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); $this->modelClass = $modelClass; $this->instance = new $this->modelClass(); $this->table = $this->instance->getTable(); $this->title = $title; $this->with = []; $this->columns = []; $this->filters = []; $this->formItems = []; }
protected function makeRepository() { $this->model = new \anlutro\Core\Auth\Users\UserModel(); $this->validator = m::mock('anlutro\\Core\\Auth\\Users\\UserValidator'); $this->validator->shouldReceive('replace')->with('table', $this->model->getTable()); return new \anlutro\Core\Auth\Users\UserRepository($this->model, $this->validator); }
/** * @param JoinClause $query * @param string $column * @param mixed $values * @param string $operator * * @throws \InvalidArgumentException */ private function transformCustomConstraint($query, $column, $values, $operator) { if (is_string($column) && !Str::contains($column, '.')) { $column = $this->related->getTable() . '.' . $column; } $values = $this->transformConstraintObject($values); if (is_array($values)) { if (count($values) > 0) { switch ($operator) { case '=': $query->whereIn($column, $values); break; case '!=': $query->whereNotIn($column, $values); break; case 'b': $query->where($column, '>=', $this->transformConstraintObject($values[0]))->where($column, '<=', $this->transformConstraintObject($values[1])); break; case '!b': $query->where($column, '<=', $this->transformConstraintObject($values[0]))->orWhere($column, '>=', $this->transformConstraintObject($values[1])); break; default: throw new \InvalidArgumentException('Join constraint has an invalid operator defined.'); break; } } } else { $query->where($column, $operator, $values); } }
/** * Aggregates data handling to the subclasses. * * @param array $data the handling internediate data. * @param array|Model $value the handling Model instance. * @return array the resulting intermediate Format instance. */ protected function aggregate(array $data, Model $value) { $data[self::KEY_OF_TABLE_NAME] = $value->getTable(); $data[self::KEY_OF_FOREIGN_KEY] = $value->getForeignKey(); $data[self::KEY_OF_OTHER_KEY] = $value->getOtherKey(); return $data; }
/** * Export a column from a table. * * @param resource $fp * @param Model $entity * @param string $key_column * @param string $data_column * @param string $comment */ private function scanTable($fp, Model $entity, $key_column, $data_column, $comment) { $table = $entity->getTable(); $this->info($table . '...'); foreach ($entity->where($data_column, '<>', '')->get() as $item) { fprintf($fp, self::PO_FORMAT, 'DATABASE: ' . $key_column . '="' . $item->getAttribute($key_column) . '"', $comment, $item->getAttribute($data_column)); } }
protected function checkQuerySelects() { $selects = $this->query->getQuery()->columns; $tableSelect = $this->model->getTable() . '.*'; if (empty($selects) || !in_array($tableSelect, $selects)) { $this->query->addSelect($tableSelect); } }
/** * Constructor */ public function __construct() { $this->response = \Response::api(); if (!empty($this->modelName)) { $this->model = new $this->modelName(); } // if no collection name provided, use the model's table name if (empty($this->collectionName)) { $this->collectionName = $this->model->getTable(); } // parse includes if (\Input::get('include') != '') { $this->manager = new \League\Fractal\Manager(); $this->manager->parseIncludes(explode(',', \Input::get('include'))); } parent::__construct(); }
public function apply(Builder $builder, Model $model) { $table = $model->getTable(); $columns = $model->getDefaultOrderableColumns() ?: []; foreach ($columns as $column => $order) { $builder->orderBy("{$table}.{$column}", $order); } }
/** * Format an Eloquent model. * * @param \Illuminate\Database\Eloquent\Model $model * * @return string */ public function formatEloquentModel($model) { $key = str_singular($model->getTable()); if (!$model::$snakeAttributes) { $key = camel_case($key); } return $this->encode([$key => $model->toArray()]); }
/** * Pretend to run the migrations. * * @param object $migration * @param string $method * * @return void */ protected function pretendToRun($migration, $method) { $table = $this->entity->getTable(); $key = $this->entity->getKey(); foreach ($this->getQueries($migration, $method) as $query) { $name = get_class($migration); $this->note("<info>{$name} [{$table}:{$key}]:</info> {$query['query']}"); } }
/** * Apply the scopes for model. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * * @return void */ public function apply(Builder $builder, Model $model) { $this->tableName = $model->getTable(); if (Auth::check() && Auth::user()->isApproved()) { $this->applyLoggedInScope($builder, Auth::user()); } else { $this->applyPublicScope($builder); } }
/** * @param \Illuminate\Database\Eloquent\Model $model * @param string $locale * @param string $alias * @return callable */ protected function getJoinClause(Eloquent $model, $locale, $alias) { return function (JoinClause $join) use($model, $locale, $alias) { $primary = $model->getTable() . '.' . $model->getKeyName(); $foreign = $model->getForeignKey(); $langKey = $model->getLocaleKey(); $join->on($alias . '.' . $foreign, '=', $primary)->where($alias . '.' . $langKey, '=', $locale); }; }
/** * Get the table associated with the model. * * @return string */ public function getTable() { if (defined('static::table')) { return static::table; } elseif (defined('static::TABLE')) { return static::TABLE; } return parent::getTable(); }
/** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(EloquentBuilder $builder, Eloquent $model) { $this->table = $model->getTable(); $this->locale = $model->getLocale(); $this->i18nTable = $model->getI18nTable(); $this->fallback = $model->getFallbackLocale(); $this->createJoin($builder, $model); $this->createWhere($builder, $model); $this->createSelect($builder, $model); }
/** * Get a constraint for abilities that have been granted to the given authority. * * @param \Illuminate\Database\Eloquent\Model $authority * @param bool $allowed * @return \Closure */ protected function getAuthorityConstraint(Model $authority, $allowed) { return function ($query) use($authority, $allowed) { $permissions = Models::table('permissions'); $abilities = Models::table('abilities'); $table = $authority->getTable(); $prefix = Models::prefix(); $query->from($table)->join($permissions, $table . '.id', '=', $permissions . '.entity_id')->whereRaw("{$prefix}{$permissions}.ability_id = {$prefix}{$abilities}.id")->where("{$permissions}.entity_type", $authority->getMorphClass())->where("{$permissions}.forbidden", !$allowed)->where("{$table}.{$authority->getKeyName()}", $authority->getKey()); }; }
/** * Create fields for type. * * @return void */ protected function schemaFields() { $table = $this->model->getTable(); $schema = $this->model->getConnection()->getSchemaBuilder(); $columns = collect($schema->getColumnListing($table)); $columns->each(function ($column) use($table, $schema) { if (!$this->skipField($column)) { $this->generateField($column, $schema->getColumnType($table, $column)); } }); }
/** * @param string $func * @param string $column * @param \anlutro\LaravelRepository\CriteriaInterface[] $criteria * @return array */ protected function aggregateInterval($func, $column, array $criteria = []) { $query = $this->db->table($this->model->getTable()); $this->interval->applyQuery($query); array_map(function ($criteria) use($query) { $criteria->apply($query); }, $criteria); $expression = $this->db->raw("{$func}({$column}) as `__aggregate__`"); $query->addSelect($expression); return $this->interval->parse($query->get(), $this->start, $this->end); }
/** * @param $parent */ private function setSortorderForAdd($parent) { if (!$this->model->id && \Schema::hasColumn($this->model->getTable(), 'sortorder')) { $query = $this->app['db']->table($this->model->getTable()); if ($this->hasParent($parent)) { $query = $query->where($parent[0], $parent[1]); } $max = $query->max($this->orderby[0]) + 1; $this->model->{$this->orderby[0]} = $max; } }
/** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model) { if ($model->getTable() == 'products') { $builder->selectglobalstock(true)->LeftJoinVarianFromProduct(true)->LeftJoinTransactionDetailFromVarian(true)->LeftTransactionStockOn(['wait', 'payment_process', 'paid', 'packed', 'shipping', 'delivered'])->groupby('products.id'); } else { if (isset($model->sort)) { $builder->selectglobalstock(true)->LeftJoinTransactionDetailFromVarian(true)->LeftTransactionStockOn(['wait', 'payment_process', 'paid', 'packed', 'shipping', 'delivered'])->groupby('varians.id')->orderby($model->sort, $model->sort_param); } else { $builder->selectglobalstock(true)->LeftJoinTransactionDetailFromVarian(true)->LeftTransactionStockOn(['wait', 'payment_process', 'paid', 'packed', 'shipping', 'delivered'])->groupby('varians.id'); } } }
/** * Search any input against the given attributes. * * @param string $input * @param array $compareAttributes * @param array $attributes * @return \Illuminate\Database\Eloquent\Collection */ public function search($input, $compareAttributes = ['*'], $attributes = ['*']) { $query = $this->query(); $compareAttributes = $compareAttributes ?: ['*']; if ($compareAttributes == ['*']) { $compareAttributes = Schema::getColumnListing($this->model->getTable()); } foreach ($compareAttributes as $column) { $query->orWhere($column, 'like', '%' . join('%', str_split($input)) . '%'); } return $query->get($this->selectAttributes($attributes)); }
public function scopeSortable($sort, $order) { return $this->addScopeQuery(function ($query) use($sort, $order) { $order = in_array(strtolower($order), ['desc', 'asc']) ? $order : 'asc'; if (!in_array($sort, $this->sortable)) { return $query; } if (strpos($sort, '.') === false) { $sort = $this->modelInstance->getTable() . '.' . $sort; } return $query->orderBy($sort, $order); }); }
/** * On save, upload files. * * @param Model $model eloquent * * @return mixed false or void */ public function saving(Model $model) { if (!($attachments = $model->attachments)) { return; } foreach ($attachments as $fieldname) { if (Request::hasFile($fieldname)) { // delete prev image $file = FileUpload::handle(Request::file($fieldname), 'uploads/' . $model->getTable()); $model->{$fieldname} = $file['filename']; if ($model->getTable() == 'files') { $model->fill($file); } } else { if ($model->{$fieldname} == 'delete') { $model->{$fieldname} = null; } else { $model->{$fieldname} = $model->getOriginal($fieldname); } } } }
/** * Include depth level into the result. * * @param string $as * * @return $this */ public function withDepth($as = 'depth') { if ($this->query->columns === null) { $this->query->columns = ['*']; } $table = $this->wrappedTable(); list($lft, $rgt) = $this->wrappedColumns(); $alias = '_d'; $wrappedAlias = $this->query->getGrammar()->wrapTable($alias); $query = $this->model->newScopedQuery('_d')->toBase()->selectRaw('count(1) - 1')->from($this->model->getTable() . ' as ' . $alias)->whereRaw("{$table}.{$lft} between {$wrappedAlias}.{$lft} and {$wrappedAlias}.{$rgt}"); $this->query->selectSub($query, $as); return $this; }
/** * On update, delete previous file if changed * * @param Model $model eloquent * @return mixed false or void */ public function updated(Model $model) { if (!($attachments = $model->attachments)) { return; } foreach ($attachments as $fieldname) { // Nothing to do if file did not change if ($model->getOriginal($fieldname) == $model->{$fieldname}) { return; } Croppa::delete('/uploads/' . $model->getTable() . '/' . $model->getOriginal($fieldname)); } }
/** * Apply mutators to the attribute "value" for a specific GEDCOM data table. * * @param Model $entity */ private function checkDataValueForModel(Model $entity) { $this->info('Checking data values in table ' . $entity->getTable()); $entity->all()->each(function ($item) { $old = $item->value; $item->value = $old; // Trigger the mutator if ($item->isDirty()) { $item->save(); $this->info('Fixing: ' . $old . ' -> ' . $item->value); } }); }