Skip to content

unknown column if alias set in ActiveRecord::find method #30

@albertborsos

Description

@albertborsos

I have an alias in my AR class.

    /**
     * @inheritdoc
     * @return TermQuery the active query used by this AR class.
     */
    public static function find()
    {
        return (new TermQuery(get_called_class()))->from(['term' => static::tableName()])->allowed();
    }

This makes an error:

[yii\db\Exception] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'module_term.sort_order' in 'field list'
The SQL being executed was: SELECT MAX(`module_term`.`sort_order`) FROM `module_term` `term`

I made a workaround for this issue:

<?php

namespace app\components\behaviors;

use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;

class SortableGridBehavior extends \himiklab\sortablegrid\SortableGridBehavior
{
    /**
     * @throws InvalidConfigException
     */
    public function beforeInsert()
    {
        /** @var ActiveRecord $model */
        $model = $this->owner;
        if (!$model->hasAttribute($this->sortableAttribute)) {
            throw new InvalidConfigException("Invalid sortable attribute `{$this->sortableAttribute}`.");
        }

        $query = $model::find();
        if (is_callable($this->scope)) {
            call_user_func($this->scope, $query);
        }

        /** Override model alias if defined in the model's class */
        $query->from([$model::tableName() => $model::tableName()]);

        $maxOrder = $query->max('{{' . trim($model::tableName(), '{}') . '}}.[[' . $this->sortableAttribute . ']]');
        $model->{$this->sortableAttribute} = $maxOrder + 1;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions