mirror of
https://github.com/yiisoft/yii2.git
synced 2025-08-23 03:41:25 +08:00
made indexBy callable like db AR
This commit is contained in:
@ -642,7 +642,12 @@ class ActiveQuery extends \yii\base\Component
|
|||||||
return $rows;
|
return $rows;
|
||||||
}
|
}
|
||||||
foreach ($rows as $row) {
|
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 {
|
} else {
|
||||||
/** @var $class ActiveRecord */
|
/** @var $class ActiveRecord */
|
||||||
@ -654,7 +659,12 @@ class ActiveQuery extends \yii\base\Component
|
|||||||
} else {
|
} else {
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$model = $class::create($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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -159,6 +159,16 @@ class ActiveRecordTest extends RedisTestCase
|
|||||||
$this->assertTrue($customers['user1'] instanceof Customer);
|
$this->assertTrue($customers['user1'] instanceof Customer);
|
||||||
$this->assertTrue($customers['user2'] instanceof Customer);
|
$this->assertTrue($customers['user2'] instanceof Customer);
|
||||||
$this->assertTrue($customers['user3'] 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()
|
public function testFindCount()
|
||||||
|
Reference in New Issue
Block a user