protected static function executeQuery($command, array $attributes) { if (!count($attributes)) { return true; } $model = new static(); if ($model->fireModelEvent('saving') === false) { return false; } $attributes = collect($attributes); $first = $attributes->first(); if (!is_array($first)) { $attributes = collect([$attributes->toArray()]); } $keys = collect($attributes->first())->keys()->transform(function ($key) { return "`" . $key . "`"; }); $bindings = []; $query = $command . " into " . $model->getTable() . " (" . $keys->implode(",") . ") values "; $inserts = []; foreach ($attributes as $data) { $qs = []; foreach ($data as $value) { $qs[] = '?'; $bindings[] = $value; } $inserts[] = '(' . implode(",", $qs) . ')'; } $query .= implode(",", $inserts); \DB::connection($model->getConnectionName())->insert($query, $bindings); $model->fireModelEvent('saved', false); }
public static function isColumnNullable($column_name) { $instance = new static(); // create an instance of the model to be able to get the table name $answer = DB::select(DB::raw("SELECT IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='" . $instance->getTable() . "' AND COLUMN_NAME='" . $column_name . "' AND table_schema='" . env('DB_DATABASE') . "'"))[0]; return $answer->IS_NULLABLE == 'YES' ? true : false; }
public static function allCached() { $instance = new static(); $tableName = $instance->getTable(); $eloquent = \Cache::remember($tableName . '_all', static::$expireCache, function () use($tableName, $instance) { return $instance->all(); }); return $eloquent; }
/** * Update all given Eloquent Model items in cache. * * @access public * @static * @return bool */ public static function updateCache($name = null) { self::initialize($name); $instance = new static(); if (!Schema::hasTable($instance->getTable())) { return false; } Cache::forever(self::$cacheName, static::all()); return true; }
/** * Lets us get a new instance populated with old input * if there is any input * * @return EloquentModel */ public function newInstanceWithOldInput() { $instance = new static(); foreach (\Input::old() as $key => $value) { if (\Schema::hasColumn($instance->getTable(), $key)) { $instance->{$key} = $value; } } return $instance; }
/** * Get enum values from a column. * * @param string $column * * @return array */ public static function getEnumValues($column) { $instance = new static(); $type = DB::select(DB::raw('SHOW COLUMNS FROM ' . $instance->getTable() . ' WHERE Field = "' . $column . '"'))[0]->Type; preg_match('/^enum\\((.*)\\)$/', $type, $matches); $enum = []; foreach (explode(',', $matches[1]) as $value) { $v = trim($value, "'"); $enum = array_add($enum, $v, $v); } return $enum; }
public static function possibleEnumValues($name) { $instance = new static(); $type = DB::select(DB::raw('SHOW COLUMNS FROM ' . $instance->getTable() . ' WHERE Field = "' . $name . '"'))[0]->Type; preg_match('/^enum\\((.*)\\)$/', $type, $matches); $enum = array(); foreach (explode(',', $matches[1]) as $value) { $v = trim($value, "'"); $enum[] = $v; } return $enum; }
public static function getEnumFromField($name) { $instance = new static(); // create an instance of the model to be able to get the table name $type = DB::select(DB::raw('SHOW COLUMNS FROM ' . $instance->getTable() . ' WHERE Field = "' . $name . '"'))[0]->Type; preg_match('/^enum\\((.*)\\)$/', $type, $matches); $enum = array(); foreach (explode(',', $matches[1]) as $value) { $v = trim($value, "'"); $enum[] = $v; } return $enum; }
/** * Get all searchable fields * * @return array */ public static function getSearchFields() { $model = new static(); $fields = $model->search; if (empty($fields)) { $fields = Schema::getColumnListing($model->getTable()); $others[] = $model->primaryKey; $others[] = $model->getUpdatedAtColumn() ?: 'created_at'; $others[] = $model->getCreatedAtColumn() ?: 'updated_at'; $others[] = method_exists($model, 'getDeletedAtColumn') ? $model->getDeletedAtColumn() : 'deleted_at'; $fields = array_diff($fields, $model->getHidden(), $others); } return $fields; }
public function scopeMostVoted($query) { // not working //return $query->with(['voteCounter' => function($q){ // return $q->orderBy('up', 'DESC'); //}]); $relatedClass = new static(); $class = $relatedClass->getMorphClass(); $table = $relatedClass->getTable(); $primary = $relatedClass->getKeyName(); $query->selectRaw("{$table}.*, voteable_id, voteable_type, IFNULL(up, 0), IFNULL(down, 0), IFNULL(up, 0) - IFNULL(down, 0) as total")->leftJoin('voteable_counter', 'voteable_counter.voteable_id', '=', "{$table}.{$primary}")->where(function ($queryWhere) use($class) { return $queryWhere->where('voteable_type', '=', $class)->orWhere('voteable_type', '=', null); })->orderBy('total', 'DESC')->orderBy('up', 'DESC'); }
/** * Return array of schema data for this model * * @return array */ public static function schema() { $model = new static(); $table = $model->getTable(); $schema = \DB::getDoctrineSchemaManager($table); $columns = $schema->listTableColumns($table); $fields = array(); foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); $length = $column->getLength(); $default = $column->getDefault(); $fields[] = compact('name', 'type', 'length', 'default'); } return $fields; }
/** * Método para verificar el logueo de un usuario. * * Si es logueo es satisfactorio retorna un arreglo con los datos del usuario. * * @param array $credentials Contiene los datos del usuario (user, password) * @param string $fieldId Contiene el campo de la tabla que representa el id. * @param string $fieldUser Contiene el campo de la tabla que representa el usuario. * @param string $fieldPass Contiene el campo de la tabla que representa el password. * @param string $type Contiene el tipo de usuario. * * @throws RestException Si $credentials no es un array. * @throws RestException Si falta algún argumento. * @throws RestException Si los argumentos son cadenas vacias. * * return array * */ public static function logIn($credentials, $fieldId, $fieldUser, $fieldPass, $type) { if (!is_array($credentials)) { throw new RestException(__FILE__, "logIn: credentials debe ser un array.", 500); } if (!isset($credentials['user']) or !isset($credentials['password'])) { throw new RestException(__FILE__, "logIn: faltan argumentos en las credenciales.", 400, ['message' => 'Faltan argumentos en las credenciales.']); } if ($credentials['user'] == "" or $credentials['password'] == "") { throw new RestException(__FILE__, "logIn: los argumentos no pueden estar vacios.", 400, ['message' => 'Los argumentos no pueden estar vacios.']); } $obj = new static(); $results = $obj->select([$fieldId, $fieldUser, $fieldPass])->where([$fieldUser => $credentials['user'], $fieldPass => md5($credentials['password'])])->get(); if ($results->count() != 1) { return false; } $data = ["data" => $results->first()->toArray(), "table" => $obj->getTable(), "type" => $type]; return $data; }
/** * Get the files for fileable * * @param string $fileableId fileable identifier * @return Collection|static[] */ public static function getByFileable($fileableId) { $model = new static(); return $model->newQuery()->rightJoin($model->getFileableTable(), $model->getTable() . '.id', '=', $model->getFileableTable() . '.fileId')->where('fileableId', $fileableId)->select([$model->getTable() . '.*'])->get(); }
public static function tableName() { $ins = new static(); return $ins->getTable(); }
/** * kick start to just fetch the config * @return array */ public static function resolveConfiguration() { static::$init = true; $self = new static(); static::$init = false; $conf = array('table' => $self->getTable(), 'fieldConf' => $self->getFieldConfiguration(), 'db' => $self->db, 'fluid' => $self->fluid, 'primary' => $self->primary); unset($self); return $conf; }
public static function table() { $model_instance = new static(); return $model_instance->getTable(); }
/** * Gets items for list. * * @param string $searchQuery * @param string $sort * @return \Illuminate\Pagination\LengthAwarePaginator */ public static function getList($searchQuery = '', $sort = '') { $model = new static(); $query = $model->newQuery(); $queryBuilder = self::getListDescriptor()->getQueryBuilder(); if ($queryBuilder) { $queryBuilder($query); } $searchBy = self::getSearchDescriptor(); if (count($searchBy) && $searchQuery) { $query->where($query->getQuery()->raw('1 = 1')); $keywords = explode(' ', trim($searchQuery)); foreach ($searchBy as $field => $search) { $query->orWhere(function ($query) use($field, $keywords) { foreach ($keywords as $keyword) { $query->where($field, 'like', '%' . trim($keyword) . '%'); } }); } self::getSearchForm()->getField('query')->setOption('value', $searchQuery); } $sortBy = $model->getTable() . '.id'; $sortDirection = ''; if ($sort) { list($sortBy, $sortDirection) = explode('#', $sort); } $query->orderBy($sortBy, $sortDirection); $items = $query->paginate(static::getItemsPerPage()); foreach ($items as $item) { self::attachStorages($item); } return $items; }
/** * Static teardown support function to destroy user accounts. Accounts are * expected to exist, and the method will fail if they are missing. * * @param array|string $users User(s) to delete * * @return void * * @throws \Exception */ protected static function removeUsers($users) { // If CI is not running, all tests were skipped, so no work is necessary: $test = new static(); // create instance of current class if (!$test->continuousIntegrationRunning()) { return; } // Delete test user $userTable = $test->getTable('User'); foreach ((array) $users as $username) { $user = $userTable->getByUsername($username, false); if (!empty($user)) { $user->delete(); } } }
/** * Get an array of LazyData objects with a WHERE statement * WARNING: The contents of $where can not be validated here, SQL injection possible. * @param string $where * @param int $count * @param int $offset * @param string $order * @return array */ public static function getWhere($where, $count = null, $offset = 0, $order = null) { $datas = array(); /** @var $manager LazyData */ $manager = new static(); $pdo = $manager->getPDO(); // If we're only getting a few items $limit = ''; if ($count) { $limit = "LIMIT {$offset},{$count}"; } // If we aren't changing the order get the default if (!$order) { $order = $manager->getOrder(); } $statement = $pdo->prepare("SELECT {$manager->getFieldsString()} FROM {$manager->getTable()} WHERE {$where} ORDER BY {$order} {$limit}"); $statement->execute(); while ($data = $statement->fetchObject(get_called_class())) { if (!($data->_safeDelete && $data->getSafeDeleteValue() > 0)) { $datas[] = $data; } } return $datas; }
/** * @return Number Return number of rows */ public static function count() { $instance = new static(); $table = $instance->getTable(); $select = static::$select; $where = static::$where; $orderby = static::$orderby; $limit = static::$limit; $sql = "select {$select} from `{$table}` {$where} {$orderby} {$limit}"; static::reset(); return mysqli_num_rows(mysqli_query(Core::getCon(), $sql)); }
/** * Returns most popular tags of date period * * @param \DateTime|string $since begin date * @param \DateTime|string|null $until end date * @param string|null $instanceId instance id * @param int $take take count * @return Collection|static[] */ public static function getPopularPeriod($since, $until = null, $instanceId = null, $take = 15) { $model = new static(); $query = $model->newQuery()->rightJoin($model->getTaggableTable(), $model->getTaggableTable() . '.tagId', '=', $model->getTable() . '.id')->select([$model->getTable() . '.*', new Expression('count(*) as cnt')])->groupBy($model->getTable() . '.word')->orderBy('cnt', 'desc')->orderBy('id', 'desc')->take($take); $model->wherePeriod($query, $since, $until); if ($instanceId !== null) { $query->where($model->getTable() . '.instanceId', $instanceId); } return $query->get(); }
public static function deleteAll($query = []) { $instance = new static(); $query = $instance->_updateQuery($query); $collection = $instance->getTable(); $return = $collection->deleteMany($query); }
/** * Get the table of this model (statically). * * @return Table */ public static function resolveTable() { $instance = new static(); return new Table($instance->getTable()); }
public static function exists($field, $value, $lang = null, $pk_id = 0) { // fallback to default language // we hide language selector if there are only 1 language in Translate settings $lang === null and $lang = ci()->translate->def(); $obj = new static(); $table = $obj->getTable(); $primary_key = $obj->primaryKey; try { $exists = Capsule::table($table)->select('*')->where($field, $value)->where('lang', strtolower($lang))->where($primary_key, '!=', (int) $pk_id)->first(); } catch (\Exception $e) { // we support `lang` field here. in case table does not have `lang` field if (strpos($e->getMessage(), "Unknown column 'lang'") !== false) { $exists = Capsule::table($table)->select('*')->where($field, $value)->where($primary_key, '!=', (int) $pk_id)->first(); } else { throw new \Exception($e->getMessage()); } } return $exists; }
/** * Get the Table for the Model. * * @return string */ public static function getTableName() { $model = new static(false); return $model->getTable(); }
/** * Vérifie que la valeur de la clé primaire est présente dans la table * @param m $mCode Valeur de la clé primaire * @return boolean */ public static function exists($mCode) { $oEmptyInstance = new static(); $oEmptyInstance->getDB()->setQuery('select `' . $oEmptyInstance->getKeyName() . '` from `' . $oEmptyInstance->getTable() . '` where `' . $oEmptyInstance->getKeyName() . '` = "' . mysql_real_escape_string($mCode) . '"'); return $oEmptyInstance->getDB()->getNumRows() > 0; }
/** * Fetch model table columns. * * @return void */ protected static function loadColumnListing() { if (empty(static::$columnListing)) { $instance = new static(); static::$columnListing = $instance->getConnection()->getSchemaBuilder()->getColumnListing($instance->getTable()); } }
/** * Query scope for finding a model by its slug. * * @param Builder $scope * @param string $slug * @param string $locale if not set, matches for any locale * @param bool $forHasQuery if true, the scope is part of a has relation subquery * @return mixed */ public function scopeWhereSlug($scope, $slug, $locale = null, $forHasQuery = false) { /** @var CmsModel|SluggableTrait $model */ $model = new static(); if ($model->storeSlugLocally()) { return $this->CviebrockScopeWhereSlug($scope, $slug); } // build scope with join to slugs table .. $scope = $scope->join(static::$slugsTable, function ($join) use($model, $locale) { $idKey = $this->isTranslationModel() ? config('pxlcms.translatable.translation_foreign_key') : $this->getKeyName(); $join->on($model->getTable() . '.' . $idKey, '=', static::$slugsTable . '.' . static::$slugsEntryKey); $join->on(static::$slugsTable . '.' . static::$slugsModuleKey, '=', DB::raw((int) $model->getModuleNumber())); if (!empty($locale) && $model->isTranslationModel()) { $languageId = $model->lookUpLanguageIdForLocale($locale); $join->on(static::$slugsTable . '.' . static::$slugsLanguageKey, '=', DB::raw((int) $languageId)); } }); return $scope->where(static::$slugsTable . '.' . static::$slugsColumn, $slug)->select($this->getTable() . '.' . ($forHasQuery ? 'id' : '*')); }
/** * Returns a record (cached) * @return self */ public static function findRecord($key) { $record = new static(); list($namespace, $group, $item) = $record->parseKey($key); return $record->applyKey($key)->remember(5, implode('-', [$record->getTable(), $namespace, $group, $item]))->first(); }
/** * Inner join with the translation table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param null $locale * * @return this */ public static function scopeJoinTranslation(Builder $query, $locale = null) { $instance = new static(); $translationModelName = $instance->getTranslationModelName(); $translationModel = new $translationModelName(); if (is_null($locale)) { $locale = $instance->locale(); } return $query->join($translationModel->getTable() . ' as t', 't.' . $instance->getRelationKey(), '=', $instance->getTable() . '.' . $instance->getKeyName())->where($instance->getLocaleKey(), $locale); }