Yury
Yury

Reputation: 23

getting an array instead of string from a query yii2

the task is to save the $model->image with row id in it. to anticipate the next autoincrement id i use the query below. mysql returns right result, but when i try to save this query result in model it saves it like 'Array' string. For example : article_Array_1516534305.png instead of article_13_1516534305.png

i tried to use array_shift() function, but result is the same

        $connection = Yii::$app->getDb();
        $dbName = $this->getDsnAttribute('dbname', Yii::$app->getDb()->dsn);

        $query = new Query;
        $query->select('AUTO_INCREMENT')
            ->from('information_schema.TABLES')
            ->where("TABLE_SCHEMA = '".$dbName."'")
            ->andWhere("TABLE_NAME = '".$this->tableName()."'");
        $id = $query->one();

        $this->image = 'article_'.$id.'_'.time(). '.' . $image->extension;  

Upvotes: 1

Views: 1790

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133360

With $query->one() you get a single model

If you need only the column value you should use scalar()

$query->scalar();

http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html

http://www.yiiframework.com/doc-2.0/yii-db-query.html#scalar()-detail

or if you want the model however you can use

$id = $query->one(); 
$id = $id['AUTO_INCREMENT'];

Upvotes: 3

Yury
Yury

Reputation: 23

the problem was that i had associated array

$id = $query->one(); $id = $id['AUTO_INCREMENT']; now it works

Upvotes: 0

Related Questions