Load a record by primary key.

@param type $index
@param type $fields

@return type
514154
protected static function loadByPrimaryKey($index, $fields = null)
    {
        //
        $table = static::getTable();

        // get primary key
        $key = static::getPrimaryKey();

        //
        $alias = static::getClassName();

        //
        $join = null;

        //
        $requestedFields = $fields ? $fields : static::getDefaultFields();

        // parse SQL select fields
        $selectFields = static::getDatabase()
            ->getWriter()
            ->selectFields($requestedFields, $alias, $join);

        // prepare SQL query
        $sql = " SELECT {$selectFields} "
             ."   FROM {$table} AS {$alias} {$join} "
             ."  WHERE {$alias}.{$key}=:index "
             .'  LIMIT 1';

        $params = [
            'index' => $index,
        ];

        // fetch data on database and return it
        $result = static::fetch($sql, $params, [
            'SingleRow'     => true,
            'SingleValue'   => is_string($fields),
            'CastToObject'  => is_null($fields),
            //'ExpanseObject' => static::isReadable(),
            'ExpanseObject' => false,
        ]);

        //
        return $result;
    }
58181
public function propagateAsRepeatableSchema(Field $field, $index)
    {
        if ($field->isTypeOf('tinymce')) {
            throw new FieldException("Tinymce [{$field->getSlug()}] field cannot be nested in repeatable field.");
        }

        foreach ($this->getValues() as $key => $value) {
            $clone = clone $field;

            $clone->setValue($value[$clone->getSlug()])->dispatch();

            $this->heap[$key][$index] = $clone;
        }
    }
110951
public function fetchColumn($index = 0): Generator
    {
        $offset = $this->getColumnIndex($index, __METHOD__.'() expects the column index to be a valid string or integer, `%s` given');
        $filter = static function (array $record) use ($offset): bool {
            return isset($record[$offset]);
        };

        $select = static function (array $record) use ($offset): string {
            return $record[$offset];
        };

        $iterator = new MapIterator(new CallbackFilterIterator($this->records, $filter), $select);
        foreach ($iterator as $offset => $value) {
            yield $offset => $value;
        }
    }
1074156
protected function dropIndex(&$property, Index $index)
    {
        $property .= sprintf("('%s')", $this->getPropertyBase('drop' . ucfirst($index->getType)), $index->name);

        return $this->addFieldPropertyClousure($property);
    }
1287017
final public function addIndex(Index $index): Table
    {
        if ($this->hasIndex($index::getName())) {
            throw new InvalidArgumentException('Foreign key '.$index::getName().' already exists in the table '.$this::getName());
        }

        $this->indexes[$index::getName()] = $index;

        return $this;
    }
961933
public function create(?string $index, array $attributes, array $toMany): string
    {
        $allowedChanges = $this->filterAttributesOnCreate($index, $attributes);
        $saveMain       = $this
            ->createBuilder($this->getModelClass())
            ->createModel($allowedChanges);
        $saveMain       = $this->builderSaveResourceOnCreate($saveMain);
        $saveMain->getSQL(); // prepare

        $this->clearBuilderParameters()->clearFetchParameters();

        $this->inTransaction(function () use ($saveMain, $toMany, &$index) {
            $saveMain->execute();

            // if no index given will use last insert ID as index
            $connection = $saveMain->getConnection();
            $index !== null ?: $index = $connection->lastInsertId();

            $builderHook = Closure::fromCallable([$this, 'builderSaveRelationshipOnCreate']);
            foreach ($toMany as $relationshipName => $secondaryIds) {
                $this->addInToManyRelationship($connection, $index, $relationshipName, $secondaryIds, $builderHook);
            }
        });

        return $index;
    }
1200329
private AssignmentField selectField(AssignmentField[] fields, int index)
   {
      if (index < 1 || index > fields.length)
      {
         throw new IllegalArgumentException(index + " is not a valid field index");
      }
      return (fields[index - 1]);
   }
1205991
public function getFields($indexed = false)
    {
        $result = array();
        foreach( $this->_fields as $field ) {
            if( (!$indexed) || $field->isIndexed ) {
                $result[ $field->name ] = $field->name;
            }
        }
        return $result;
    }
1103546
protected function assignIndexes($indexes)
    {
        foreach ($indexes as $index) {
            if (!$index instanceof IndexInterface) {
                throw new ModelException(sprintf('Index must be an instance of IndexInterface, got "%s"', $this->getType($index)));
            }

            foreach ($index->fields() as $key => $field) {
                $field = $index->type() == 'foreign' ? $key : $field;

                $this->assertField($field);
            }

            if ($index->type() !== 'foreign') {
                $index->table($this->table);
            }

            $this->indexes[$index->name()] = $index;
        }
    }
526518
public function getCreateIndexSQL(Index $index, $table)
    {
        return parent::getCreateIndexSQL($index, $table) . $this->getAdvancedIndexOptionsSQL($index);
    }
256850
protected function _loadFieldData($fields) {
        if (!is_array($fields)) $fields= array($fields);
        else $fields= array_values($fields);
        $criteria= $this->xpdo->newQuery($this->_class, $this->getPrimaryKey());
        $criteria->select($fields);
        if ($rows= xPDOObject :: _loadRows($this->xpdo, $this->_class, $criteria)) {
            $row= $rows->fetch(\PDO::FETCH_ASSOC);
            $rows->closeCursor();
            $this->fromArray($row, '', false, true);
            $this->_lazy= array_diff($this->_lazy, $fields);
        }
    }
1201633
public static function firstOrNull($fields = null)
    {
        static $request;
        if (!$request) {
            $request = Di::getDefault()->getShared('request');
        }

        if (!$request->isAjax()) {
            return null;
        }

        $model = new static();
        return static::get($request->getId($model->getPrimaryKey()));
    }
1254789
public function update($index, $data)
    {
        $db = $this->load();
        $db[$index] = array_merge($db[$index], $data);
        return $this->rewrite($db);
    }
56614
public function indexBy($field)
    {
        $this->data = $this->executeIndexBy($this->data, $field);
        $this->indexBy = $field;
        return $this;
    }
423601
public static function getRecordByField($field, $value, $cacheIndex = false)
    {
        $query = 'SELECT * FROM `%s` WHERE `%s` = "%s" LIMIT 1';
        $params = [
            static::$tableName,
            static::_cn($field),
            DB::escape($value),
        ];

        if ($cacheIndex) {
            $key = sprintf('%s/%s:%s', static::$tableName, $field, $value);
            return DB::oneRecordCached($key, $query, $params, [static::class,'handleError']);
        } else {
            return DB::oneRecord($query, $params, [static::class,'handleError']);
        }
    }
1309908
protected function createDefaultSearchFieldsMapping(Index $index, $lang = 'en')
    {
        $mapping = new Mapping();
        $mapping->setType($index->getType($this->indexType));

        $mapping->setProperties($this->properties);

        return $mapping;
    }
422914
public function addFields(array $fields)
    {
        foreach ($fields as $field)
        {
            $name = $field->getName();
            $addFields[$name] = $field; # we key by name to prevent duplicates!
        }
        
        $keysString = "";
        $fieldStrings = array();
        
        foreach ($addFields as $fieldName => $field)
        {
            $fieldStrings[] = $field->getFieldString();
                
            /* @var $field DatabaseField */
            if ($field->isPrimaryKey())
            {
                $errMsg = 'Do not set field to be primary key when adding fields. ' .
                          'Instead, use the changePrimaryKey method';
                throw new \Exception($errMsg);
            }
            elseif ($field->isKey())
            {
                if ($keysString !== "")
                {
                    $keysString .= ", ";
                }
                
                if ($field->isUnique())
                {
                    $keysString .= "UNIQUE ";
                }
                
                $keysString .= "KEY (`" . $fieldName . "`) ";
            }
        }
        
        $fieldsString = implode(", ", $fieldStrings);
        
        $fieldsString .= $keysString;
        
        $query = 
            "ALTER TABLE " . 
            "`" . $this->m_name . "` " . 
            "ADD " .
            "(" . $fieldsString . ") ";
        
        $result = $this->m_mysqliConn->query($query);
        
        if ($result !== TRUE)
        {
            throw new \Exception('Error creating table with query: ' . $query);
        }
    }