/** * Get JWT identifier. * Defaults to the model id. * * @return string|int */ public function getJWTIdentifier() { if (!method_exists($this->model, 'getJWTIdentifier')) { return $this->model->{$this->model->getKeyName()}; } return $this->model->getJWTIdentifier(); }
/** * Find a model by its primary key. * * @param array $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|Collection|static */ public function findMany($id, $columns = array('*')) { if (empty($id)) { return new Collection(); } $this->query->whereIn($this->model->getKeyName(), $id); return $this->get($columns); }
/** * Interpolate model attribute values on validation rules. * * @param array $rules * @param array $model * @return array */ protected function interpolateValidationRules($rules, $model) { foreach ($rules as &$rule) { $attrs = last(chars_within($rule, ['{', '}'])); foreach ($attrs as $attr) { $rule = str_replace('{' . $attr . '}', is_null($model[$attr]) && $attr == $this->model->getKeyName() ? 'NULL' : $model[$attr], $rule); } } return $rules; }
public static function filterModelAttributes($array, Model $model) { $column = array(); foreach ($array as $attribute => $value) { if (in_array($attribute, $model->getFillable())) { $column[] = $attribute; } } array_has($column, $model->getKeyName()) == false & count($column) > 0 ? $column[] = $model->getKeyName() : null; return count($column) > 0 ? $column : array('*'); }
/** * New From Hit Builder. * * Variation on newFromBuilder. Instead, takes * * @param $model * @param array $hit * * @return static */ public function fillModel(Model $model, $hit = []) { $key_name = $model->getKeyName(); $attributes = $hit['_source']; if (isset($hit['_id'])) { $attributes[$key_name] = is_numeric($hit['_id']) ? intval($hit['_id']) : $hit['_id']; } // Add fields to attributes if (isset($hit['fields'])) { foreach ($hit['fields'] as $key => $value) { $attributes[$key] = $value; } } $instance = $this->newFromBuilderRecursive($model, $attributes); // In addition to setting the attributes // from the index, we will set the score as well. $instance->documentScore = $hit['_score']; // This is now a model created // from an Elasticsearch document. $instance->isDocument = true; // Set our document version if it's if (isset($hit['_version'])) { $instance->documentVersion = $hit['_version']; } return $instance; }
/** * Create a new instance of relation. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $parent * @param array $models * @param string|null $localKey * @param string $prefix * @param array $foreignKeyLookup */ public function __construct(Builder $query, Model $parent, array $models, $localKey = null, $prefix = '', $foreignKeyLookup = []) { $this->models = $models; $this->localKey = $localKey ?: $parent->getKeyName(); $this->prefix = $prefix; $this->foreignKeyLookup = $foreignKeyLookup; parent::__construct($query, $parent); }
public function getKeyName() { if ($this->model instanceof Model) { return $this->model->getKeyName(); } $model = $this->app->make($this->modelClass); return $model->getKeyName(); }
/** * @param Model $oModel * @return array */ protected function resolveModelToArray(Model $oModel) { /** @var Key $oKey */ $oKey = $oModel->getAttribute("key"); /** @var Locale $oLocale */ $oLocale = $oModel->getAttribute("locale"); $aReturn = [$oModel->getKeyName() => $oModel->getKey(), "key" => $oKey ? $oKey->getAttribute(Key::COLUMN_NAME) : null, "locale" => $oLocale ? $oLocale->getAttribute(Locale::COLUMN_CODE) : null, Message::COLUMN_TEXT => $oModel->getAttribute(Message::COLUMN_TEXT)]; return $aReturn; }
/** * @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->getKeyName(); $foreign = $model->getForeignKey(); $langKey = $model->getLocaleKey(); $join->on($alias . '.' . $foreign, '=', $this->table . '.' . $primary)->where($alias . '.' . $langKey, '=', $locale); }; }
public function count($columns = null) { // Count rows using the model's primary key by default if ($columns === null) { $columns = $this->model->getKeyName(); } // If we cannot determine the columns to match, count all columns if (!$columns) { $columns = '*'; } return $this->select()->count($columns); }
/** * 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); }
public function enviarImagem(Model $obj, $tipo, UploadedFile $file, $substituir = false) { //EXCLUINDO ANTIGA if ($substituir) { $imagens = $this->findWhere([$obj->getKeyName() => $obj->getKey(), 'imagem_tipo' => $tipo], ['imagem_id']); foreach ($imagens as $img) { $this->delete($img->imagem_id); } } $arquivo = $obj->gerarNomeHashArquivo($file); $file->move($obj->folderPath(), $arquivo['completo']); $tamanho = getimagesize($obj->folderPath() . '/' . $arquivo['completo']); list($largura, $altura) = getimagesize($obj->folderPath() . "/" . $arquivo['completo']); if ($largura < $this->model->sizes[$tipo][0] || $altura < $this->model->sizes[$tipo][1]) { $img = Image::make($obj->folderPath() . "/" . $arquivo['completo']); $img->resizeCanvas($this->model->sizes[$tipo][0], $this->model->sizes[$tipo][1], 'center'); $img->save($obj->folderPath() . "/" . $arquivo['completo']); $tamanho = getimagesize($obj->folderPath() . '/' . $arquivo['completo']); } $imagem = $this->create([$obj->getKeyName() => $obj->getKey(), 'imagem_tipo' => $tipo, 'imagem_nome' => $arquivo['completo'], 'imagem_largura' => $tamanho[0], 'imagem_altura' => $tamanho[1]]); return $imagem; }
/** * {@inheritdoc} */ public function delete($ids) { $ids = is_array($ids) ? $ids : func_get_args(); if (empty($ids)) { return 0; } $key = $this->model->getKeyName(); $count = 0; foreach ($this->newQuery()->whereIn($key, $ids)->get() as $item) { if ($item->delete()) { $count++; } } return $count; }
/** * Update multiple models attributes in the storage. * * @param array $items * @return \Illuminate\Database\Eloquent\Collection */ public function updateMany(array $items) { $ids = array_pluck($items, $this->model->getKeyName()); $models = $this->model->find($ids); foreach ($models as $model) { $attributes = array_first($items, function ($i, $attributes) use($model) { if (!array_key_exists($model->getKeyName(), $attributes)) { return false; } return $attributes[$model->getKeyName()] == $model->getKey(); }); $this->validation()->validate('update', array_merge($attributes, [$model->getKeyName() => $model->getKey()])); $model->fill($attributes); $model->save(); } return $models; }
/** * */ public function generateForm() { $ignoredColumns = [$this->instance->getKeyName(), Model::CREATED_AT, Model::UPDATED_AT, 'deleted_at']; $columns = $this->schemaManager->listTableColumns($this->table); $textareas = []; foreach ($columns as $column) { if (in_array($column->getName(), $ignoredColumns)) { continue; } $formItem = $this->generateFormItem($column); if ($column->getType()->getName() === 'text') { $textareas[] = $formItem; } else { $this->formItems[] = $formItem; } } $this->formItems = array_merge($this->formItems, $textareas); }
/** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function performInsert(Model $model) { // Generate a new key if needed. if ($model->getKeyName() == '_id' and !$model->getKey()) { $model->setAttribute('_id', new MongoId()); } // For deeply nested documents, let the parent handle the changes. if ($this->isNested()) { $this->associate($model); return $this->parent->save(); } $result = $this->getBaseQuery()->update(array($this->localKey => $model->getAttributes())); // Attach the model to its parent. if ($result) { $this->associate($model); } return $result ? $model : false; }
/** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function performInsert(Model $model) { // Generate a new key if needed. if ($model->getKeyName() == '_id' and !$model->getKey()) { $model->setAttribute('_id', new \MongoDB\BSON\ObjectID()); } // For deeply nested documents, let the parent handle the changes. if ($this->isNested()) { $this->associate($model); return $this->parent->save(); } // Push the new model to the database. $result = $this->getBaseQuery()->push($this->localKey, $model->getAttributes(), true); // Attach the model to its parent. if ($result) { $this->associate($model); } return $result ? $model : false; }
/** * This method will return an array of cache keys that may be used to store this model in cache. The $modelAttributes * array should contain all the fields required to populate the unique keys returned from getUniqueKeys() * * @access public * @static * @param array $modelAttributes * @return array Returns an array of cache keys, keyed off the column names. */ public static function uniqueKeys(Model $sourceObject) { $objectKeys = $sourceObject->getUniqueKeys(); $primaryKey = $sourceObject->getKeyName(); if (!in_array($primaryKey, $objectKeys)) { $objectKeys[] = $primaryKey; } $uniqueKeys = []; foreach ($objectKeys as $value) { $key = $value; if (is_array($key)) { sort($key); sort($value); $key = implode(",", $key); } $uniqueKeys[$key] = $value; } ksort($uniqueKeys); return $uniqueKeys; }
/** * @param array $dictionary * @param array $data * @param array $existing * @param mixed $parentId */ protected function buildRebuildDictionary(array &$dictionary, array $data, array &$existing, $parentId = null) { $keyName = $this->model->getKeyName(); foreach ($data as $itemData) { if (!isset($itemData[$keyName])) { $model = $this->model->newInstance(); // We will save it as raw node since tree will be fixed $model->rawNode(0, 0, $parentId); } else { if (!isset($existing[$key = $itemData[$keyName]])) { throw new ModelNotFoundException(); } $model = $existing[$key]; unset($existing[$key]); } $model->fill(Arr::except($itemData, 'children'))->save(); $dictionary[$parentId][] = $model; if (!isset($itemData['children'])) { continue; } $this->buildRebuildDictionary($dictionary, $itemData['children'], $existing, $model->getKey()); } }
/** * Remove a selected record. * * @param string $key * * @return bool */ public function remove($key) { return $this->model->where($this->model->getKeyName(), $key)->delete(); }
/** * Find a model by its primary key. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model */ public function find($id, $columns = array('*')) { $this->query->where($this->model->getKeyName(), '=', $id); return $this->first($columns); }
/** * Create a new instance of relation. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $parent * @param array $models * @param string|null $localKey */ public function __construct(Builder $query, Model $parent, array $models, $localKey = null) { $this->models = $models; $this->localKey = $localKey ?: $parent->getKeyName(); parent::__construct($query, $parent); }
/** * {@inheritDoc} * * @param Model $model */ protected function doGetIdentity($model) { return new Identity($model->{$model->getKeyName()}, $model); }
/** * Map the given results to instances of the given model. * * @param mixed $results * @param \Illuminate\Database\Eloquent\Model $model * @return Collection */ public function map($results, $model) { if (count($results['hits']['total']) === 0) { return Collection::make(); } $keys = collect($results['hits']['hits'])->pluck('_id')->values()->all(); $models = $model->whereIn($model->getKeyName(), $keys)->get()->keyBy($model->getKeyName()); return collect($results['hits']['hits'])->map(function ($hit) use($model, $models) { return $models[$hit['_id']]; }); }
/** * Helper function to determine if a user is part * of this team * * @param Model $user * @return bool */ public function hasUser(Model $user) { return $this->users()->where($user->getKeyName(), "=", $user->getKey())->first() ? true : false; }
/** * Constrain a related query to the given user. * * @param \Illuminate\Database\Eloquent\Model $user * @return \Closure */ protected function getUserConstraint(Model $user) { return function ($query) use($user) { $column = "{$user->getTable()}.{$user->getKeyName()}"; $query->where($column, $user->getKey()); }; }
/** * @param Model $model * @param $resourceType * @return string */ protected function resolveKeyName(Model $model, $resourceType) { return isset($this->keyNames[$resourceType]) ? $this->keyNames[$resourceType] : $model->getKeyName(); }
public function deleting(\Illuminate\Database\Eloquent\Model $model) { // Get column names. // Missing required columns will throw an exception. $pkColumn = $model->getKeyName(); $leftColumn = $model->getLeftColumn(); $rightColumn = $model->getRightColumn(); $parentColumn = $model->getParentColumn(); // A node is being deleted. // Rebuild the entire tree. echo 'node deleted'; // @TODO: Be smarter about this method. dd($model); $rootNode = $model::where($parentColumn, '=', null)->first(); $rootNode->buildTree(); return true; }
/** * Find a model by its primary key. * * @param array $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|Collection|static */ public function findMany($id, $columns = array('*')) { $this->query->whereIn($this->model->getKeyName(), $id); return $this->get($columns); }
/** * Resolve field type by column info. * * @param string $name * @param string $colType * @return \GraphQL\Type\Definition\Type */ protected function resolveTypeByColumn($name, $colType) { $type = Type::string(); $type->name = $this->getName() . '_String'; if ($name === $this->model->getKeyName()) { $type = Type::id(); $type->name = $this->getName() . '_ID'; } elseif ($colType === 'integer') { $type = Type::int(); $type->name = $this->getName() . '_Int'; } elseif ($colType === 'float' || $colType === 'decimal') { $type = Type::float(); $type->name = $this->getName() . '_Float'; } elseif ($colType === 'boolean') { $type = Type::boolean(); $type->name = $this->getName() . '_Boolean'; } return $type; }