diff --git a/framework/yii/redis/ActiveQuery.php b/framework/yii/redis/ActiveQuery.php index 169720d60c..221bebfed2 100644 --- a/framework/yii/redis/ActiveQuery.php +++ b/framework/yii/redis/ActiveQuery.php @@ -642,7 +642,12 @@ class ActiveQuery extends \yii\base\Component return $rows; } foreach ($rows as $row) { - $models[$row[$this->indexBy]] = $row; + if (is_string($this->indexBy)) { + $key = $row[$this->indexBy]; + } else { + $key = call_user_func($this->indexBy, $row); + } + $models[$key] = $row; } } else { /** @var $class ActiveRecord */ @@ -654,7 +659,12 @@ class ActiveQuery extends \yii\base\Component } else { foreach ($rows as $row) { $model = $class::create($row); - $models[$model->{$this->indexBy}] = $model; + if (is_string($this->indexBy)) { + $key = $model->{$this->indexBy}; + } else { + $key = call_user_func($this->indexBy, $model); + } + $models[$key] = $model; } } } diff --git a/tests/unit/framework/redis/ActiveRecordTest.php b/tests/unit/framework/redis/ActiveRecordTest.php index acaa5f4c57..e4205c2919 100644 --- a/tests/unit/framework/redis/ActiveRecordTest.php +++ b/tests/unit/framework/redis/ActiveRecordTest.php @@ -159,6 +159,16 @@ class ActiveRecordTest extends RedisTestCase $this->assertTrue($customers['user1'] instanceof Customer); $this->assertTrue($customers['user2'] instanceof Customer); $this->assertTrue($customers['user3'] instanceof Customer); + + // indexBy callable + $customers = Customer::find()->indexBy(function ($customer) { + return $customer->id . '-' . $customer->name; +// })->orderBy('id')->all(); + })->all(); + $this->assertEquals(3, count($customers)); + $this->assertTrue($customers['1-user1'] instanceof Customer); + $this->assertTrue($customers['2-user2'] instanceof Customer); + $this->assertTrue($customers['3-user3'] instanceof Customer); } public function testFindCount()