Log Events to DB.

@param $model The Eloquent model.
356480
private function logEventsToDB($model)
    {
        $user = auth()->user();
        $class = get_class($model);
        $trace = debug_backtrace();
        $event = $trace[2] ? $trace[2]['function'] : "Unknown event";

        try {
            UserAction::create(
                array_merge($this->getDiff($model), [
                    'model' => $class,
                    'action' => $event,
                    'user_id' => $user ? $user->id : null,
                    'model_id' => $model->id,
                ])
            );
        } catch (\Exception $e) {
            $message = $e->getMessage();
            Log::error("Could not record user action to db: '{$message}'");
        }
    }
1268144
public function saved($model)
    {
        if (static::syncingDisabledFor($model)) {
            return;
        }

        if (! $model->shouldBeSearchable()) {
            $model->unsearchable();

            return;
        }

        $model->searchable();
    }
52687
protected function saveColumns(Model $model)
    {
        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $columns = $class::getColumns();
        $relations = $class::getRelations();
        $cols = [];
        $prep = [];
        $sets = [];
        $data = [];

        foreach ($columns as $column => $def) {
            if (isset($model->{$column}) && null === $model->{$column} && isset($def['default'])) {
                $cols[] = $this->quoteName($column);
                $prep[] = ':' . $column;
                $sets[] = '' . $this->quoteName($column) . '=:' . $column;
                $data[':' . $column] = $def['default'];
            } else {
                $cols[] = $this->quoteName($column);
                $prep[] = ':' . $column;
                $sets[] = '' . $this->quoteName($column) . '=:' . $column;
                switch ($def['type']) {
                    case 'boolean':
                        $data[':' . $column] = (int)$model->{$column};
                        break;
                    default:
                        $data[':' . $column] = $model->{$column};
                        break;
                }
            }
        }

        foreach ($relations as $rel => $def) {
            switch ($def['type']) {
                case $class::BELONGS_TO:
                    $column = $class::getRelationLinkName($def);
                    if (!in_array($column, $cols)) {
                        // @todo: test this!
                        // if (isset($model->{$column}) && !is_null($model->{$column})) {
                        if (isset($model->{$column})) {
                            $cols[] = $this->quoteName($column);
                            $prep[] = ':' . $column;
                            $sets[] = '' . $this->quoteName($column) . '=:' . $column;
                            $data[':' . $column] = $model->{$column};
                        } elseif (isset($model->{$rel}) && $model->{$rel} instanceof Model) {
                            $cols[] = $this->quoteName($column);
                            $prep[] = ':' . $column;
                            $sets[] = '' . $this->quoteName($column) . '=:' . $column;
                            $data[':' . $column] = $model->{$rel}->getPk();
                        }
                    }
                    break;
            }
        }

        $connection = $class::getDbConnection();
        if ($model->isNew()) {
            $sql = '
                INSERT INTO ' . $this->quoteName($class::getTableName()) . '
                (' . implode(', ', array_unique($cols)) . ')
                VALUES
                (' . implode(', ', array_unique($prep)) . ')
                RETURNING ' . $class::PK . '
            ';
            $res = $connection->query($sql, $data);
            $model->{$class::PK} = $res->fetch()[$class::PK];
        } else {
            $sql = '
                UPDATE ' . $this->quoteName($class::getTableName()) . '
                SET ' . implode(', ', array_unique($sets)) . '
                WHERE "' . $class::PK . '"=\'' . $model->{$class::PK} . '\'
            ';
            $connection->execute($sql, $data);
        }

        return $model;

    }
738319
private function create($model)
    {
        $attrs = $this->getMutableAttributes($model);
        $this->db
            ->connect()
            ->insert($this->table, array_keys($attrs))
            ->execute(array_values($attrs));
        $model->{$this->key} = $this->db->lastInsertId();
    }
669276
public function onItem(Model $model)
    {
        $this->itemsList();
        $this->breadcrumbs->register('item', function($breadcrumbs) use($model) {
            $name = $model->exists ? trans('antares/sample_module::messages.breadcrumb.item_edit', ['name' => $model->name]) : trans('antares/sample_module::messages.breadcrumb.item_add');
            $breadcrumbs->parent(self::$name);
            $breadcrumbs->push($name);
        });

        $this->shareOnView('item');
    }
109301
protected function buildRowsFromModel($model): void
    {
        $this->model = $model = $this->buildModel($model);

        if ($model instanceof Paginator) {
            $this->setRowsData($model->items());
            $this->paginate = true;
        } elseif ($model instanceof Collection) {
            $this->setRowsData($model->all());
        } elseif ($model instanceof Arrayable) {
            $this->setRowsData($model->toArray());
        } elseif (\is_array($model)) {
            $this->setRowsData($model);
        } else {
            throw new InvalidArgumentException('Unable to convert $model to array.');
        }
    }
1236313
public static function register($model)
    {
        if (interface_exists(EloquentScope::class)) {
            $model::addGlobalScope(new TenantScope);
        } else {
            $model::addGlobalScope(new LegacyTenantScope);
        }
    }
66414
public function info($model = null)
    {
        $debug = $this->isDebug();
        $this->setDebug(false);

        if (is_null($model)) {
            $this->info($this->getModels());
        } elseif (is_array($model) && count($model) > 0) {
            foreach ($model as $m) {
                $this->info($m);
            }
        } elseif (is_array($model) && count($model) == 0) {
            echo '<pre><table border="1">'
               .'<tr><th>No database tables</th></tr></table></pre>'
               .'</table></pre>';
        } else {
            $desc = $this->desc($model);
            Functions::dumpSchema($desc);
        }

        $this->setDebug($debug);
    }
611311
public function dump($model = null)
    {
        if ($model) {
            $all = $this->all($model);
            Functions::dumpGrid($all, $model);
        } else {
            $this->dumpSchema();
        }
    }
1089174
public function markSaved($model)
    {
        $hash = spl_object_hash($model);

        if (isset($this->pending[$hash])) {
            unset($this->pending[$hash]);
        }

        $this->saved[$hash] = $model;
    }
929015
protected function saveColumns(Model $model)
    {
        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $columns = $class::getColumns();
        $relations = $class::getRelations();
        $cols = [];
        $sets = [];
        $data = [];

        foreach ($columns as $column => $def) {
            if (isset($model->{$column}) && null === $model->{$column} && isset($def['default'])) {
                $sets[$column] = ':' . $column;
                $data[':'.$column] = $def['default'];
            } else {
                $cols[] = $column;
                $sets[$column] = ':' . $column;
                switch ($def['type']) {
                    case 'boolean':
                        $data[':' . $column] = (int)$model->{$column};
                        break;
                    default:
                        $data[':' . $column] = $model->{$column};
                        break;
                }
            }
        }

        foreach ($relations as $rel => $def) {
            switch ($def['type']) {
                case $class::BELONGS_TO:
                    $column = $class::getRelationLinkName($def);
                    if (!in_array($column, $cols)) {
                        // todo: test this!
                        //if (isset($model->{$column}) && !is_null($model->{$column})) {
                        if (isset($model->{$column})) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$column};
                        } elseif (isset($model->{$rel}) && $model->{$rel} instanceof Model) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$rel}->getPk();
                        }
                    }
                    break;
            }
        }

        $connection = $class::getDbConnection();
        if ($model->isNew()) {
            $query = new Query();
            $query->insert($class::getTableName())
                ->values($sets)
                ->params($data);
            $connection->execute($query);
            $model->{$class::PK} = $connection->lastInsertId();
        } else {
            $query = new Query();
            $query->update($class::getTableName())
                ->values($sets)
                ->where($this->quoteName($class::PK) . '='. $model->getPk())
                ->params($data);
            $connection->execute($query);
        }

        return $model;

    }
414510
public static function updateModel($model)
    {
        foreach(AnnotationManager::getPropertiesAnnotations(BeanFactory::getObjectClass($model), RelationBase::class) as $propertyName => $annotations)
        {
            if(null === $model[$propertyName])
            {
                continue;
            }
            $annotation = $annotations[0];
            Update::parse($model, $propertyName, $annotation);
        }
    }
379424
protected function addSoftDeletesScopes($model)
    {
        if (array_key_exists('Illuminate\Database\Eloquent\SoftDeletes', class_uses($model))) {
            foreach ($this->softDeletesScopes() as $method => $name) {
                $this->addScope(
                    with(new Scope($method))
                        ->setTitle($name)
                        ->setQuery([$model, $method])
                );
            }
        }
    }
1086790
public function saving(Tree $model)
    {
        if (!$model->exists and !in_array('path', array_keys($model->attributesToArray()), TRUE)) {
            $model->{$model->getTreeColumn('path')}   = '';
            $model->{$model->getTreeColumn('parent')} = NULL;
            $model->{$model->getTreeColumn('level')}  = 0;
        }
    }
1254022
public function afterSave($model, $data) {
        // Check if the 'published column' is filled...
        if (empty($data[self::PUBLISHED_COLUMN])) {
            return;
        }

        // ...and that it's in the future
        $publishTime = strtotime($data[self::PUBLISHED_COLUMN]);
        if ($publishTime <= time()) {
            return;
        }

        $tags = array(get_class($model));
        $tags = array_merge($tags, $model->getBindableModels());
        $tags = array_unique($tags);
        Garp_Cache_Manager::scheduleClear($publishTime, $tags);
    }
1026016
protected function prepareQuery($model)
    {
        // Set the relationships that should be eager loaded
        if (! empty($this->relations)) {
            $model = $model->with($this->relations);
        }

        // Add a basic where clause to the query
        foreach ($this->where as $where) {
            list($attribute, $operator, $value, $boolean) = array_pad($where, 4, null);

            $model = $model->where($attribute, $operator, $value, $boolean);
        }

        // Add a "where in" clause to the query
        foreach ($this->whereIn as $whereIn) {
            list($attribute, $values, $boolean, $not) = array_pad($whereIn, 4, null);

            $model = $model->whereIn($attribute, $values, $boolean, $not);
        }

        // Add a "where not in" clause to the query
        foreach ($this->whereNotIn as $whereNotIn) {
            list($attribute, $values, $boolean) = array_pad($whereNotIn, 3, null);

            $model = $model->whereNotIn($attribute, $values, $boolean);
        }

        // Set the "offset" value of the query
        if ($this->offset > 0) {
            $model = $model->offset($this->offset);
        }

        // Set the "limit" value of the query
        if ($this->limit > 0) {
            $model = $model->limit($this->limit);
        }

        // Add an "order by" clause to the query.
        if (! empty($this->orderBy)) {
            list($attribute, $direction) = $this->orderBy;

            $model = $model->orderBy($attribute, $direction);
        }

        return $model;
    }
1008522
protected function getTimestampFields($model)
    {
        try {
            $baseModel = new ReflectionClass($model);
            $timestampFields = [
                'created_at' => $baseModel->getConstant('CREATED_AT'),
                'updated_at' => $baseModel->getConstant('UPDATED_AT'),
                'deleted_at' => $baseModel->getConstant('DELETED_AT'),
            ];
        } catch (Exception $e) {
            echo 'baseModel: '.$model.' not found'.LF;
            $timestampFields = [
                'created_at' => 'created_at',
                'updated_at' => 'updated_at',
                'deleted_at' => 'deleted_at',
            ];
        }

        return $timestampFields;
    }