diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index c41f36ad8e..b230411fd7 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -111,6 +111,7 @@ Yii Framework 2 Change Log - Bug #16687: Add missing translations for `nl-NL` durations used in `yii\i18n\Formatter::asDuration()` (alexeevdv) - Bug #16469: Allow cache to be specified as interface and to be configured in DI container (alexeevdv) - Bug #16959: Fixed typo in if condition inside `yii\web\DbSession::typecastFields()` that caused problems with session overwriting (silverfire) +- Bug #15876: `yii\db\ActiveQuery::viaTable()` now throws `InvalidConfigException`, if query is not prepared correctly (silverfire) 2.0.15.1 March 21, 2018 ----------------------- diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index a5c1da01e1..f720864ae4 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -767,12 +767,16 @@ class ActiveQuery extends Query implements ActiveQueryInterface * @param callable $callable a PHP callback for customizing the relation associated with the junction table. * Its signature should be `function($query)`, where `$query` is the query to be customized. * @return $this the query object itself + * @throws InvalidConfigException when query is not initialized properly * @see via() */ public function viaTable($tableName, $link, callable $callable = null) { - $modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : __CLASS__; + if ($this->primaryModel === null) { + throw new InvalidConfigException('The "primaryModel" property is not set. The query must be a relation to use junction tables. You probably need to call hasOne() or hasMany() method first.'); + } + $modelClass = get_class($this->primaryModel); $relation = new self($modelClass, [ 'from' => [$tableName], 'link' => $link, diff --git a/tests/framework/db/ActiveQueryTest.php b/tests/framework/db/ActiveQueryTest.php index f4f671a469..dd55df61e0 100644 --- a/tests/framework/db/ActiveQueryTest.php +++ b/tests/framework/db/ActiveQueryTest.php @@ -215,12 +215,21 @@ abstract class ActiveQueryTest extends DatabaseTestCase */ public function testViaTable() { - $query = new ActiveQuery(Customer::className()); + $query = new ActiveQuery(Customer::className(), ['primaryModel' => new Order()]); $result = $query->viaTable(Profile::className(), ['id' => 'item_id']); $this->assertInstanceOf('yii\db\ActiveQuery', $result); $this->assertInstanceOf('yii\db\ActiveQuery', $result->via); } + public function testViaTableOnWronglyConfiguredQuery() + { + $query = new ActiveQuery(Customer::className()); + + $this->expectException('yii\base\InvalidConfigException'); + $this->expectExceptionMessage('The "primaryModel" property is not set.'); + $query->viaTable(Profile::className(), ['id' => 'item_id']); + } + public function testAlias_not_set() { $query = new ActiveQuery(Customer::className());