From b9cbc56330c16f21c1fd8ea35a7017bb45b7ee49 Mon Sep 17 00:00:00 2001 From: Klimov Paul Date: Tue, 23 Jan 2018 12:46:56 +0200 Subject: [PATCH] Fixed `yii\db\ActiveRecord::with()` unable to use relation defined via attached behavior in case `asArray` is enabled --- framework/CHANGELOG.md | 1 + framework/db/ActiveQueryTrait.php | 4 +++- tests/framework/db/ActiveRecordTest.php | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 204073a697..fb2fc6a402 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -8,6 +8,7 @@ Yii Framework 2 Change Log - Bug #14711: Fixed `yii\web\ErrorHandler` displaying exception message in non-debug mode (samdark) - Enh #13814: MySQL unique index names can now contain spaces (df2) - Bug #15300: Fixed "Cannot read property 'style' of undefined" error at the error screen (vitorarantes) +- Bug #15540: Fixed `yii\db\ActiveRecord::with()` unable to use relation defined via attached behavior in case `asArray` is enabled (klimov-paul) - Enh #15426: Added abilitiy to create and drop database views (igravity, vladis84) - Enh #10186: Use native `hash_equals` in `yii\base\Security::compareString()` if available, throw exception if non-strings are compared (aotd1, samdark) - Bug #15122: Fixed `yii\db\Command::getRawSql()` to properly replace expressions (hiscaler, samdark) diff --git a/framework/db/ActiveQueryTrait.php b/framework/db/ActiveQueryTrait.php index 365606e8fa..79fa1158bf 100644 --- a/framework/db/ActiveQueryTrait.php +++ b/framework/db/ActiveQueryTrait.php @@ -162,7 +162,9 @@ trait ActiveQueryTrait { $primaryModel = reset($models); if (!$primaryModel instanceof ActiveRecordInterface) { - $primaryModel = new $this->modelClass(); + /* @var $modelClass ActiveRecordInterface */ + $modelClass = $this->modelClass; + $primaryModel = $modelClass::instance(); } $relations = $this->normalizeRelations($primaryModel, $with); /* @var $relation ActiveQuery */ diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index e62219a333..0519b5ab0f 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -1600,5 +1600,13 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertInstanceOf(OrderItemWithConstructor::className(), $item); $this->assertEquals(1, $item->item_id); + + // @see https://github.com/yiisoft/yii2/issues/15540 + $orders = OrderWithConstructor::find() + ->with(['customer.profile', 'orderItems']) + ->orderBy('id') + ->asArray(true) + ->all(); + $this->assertCount(3, $orders); } }