ActiveQuery::viaTable() now throws exception on wrongly prepared query

Closes #15876
This commit is contained in:
SilverFire - Dmitry Naumenko
2019-01-20 12:33:18 +02:00
parent 3c091b802a
commit dfcf037c76
3 changed files with 16 additions and 2 deletions

View File

@@ -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
-----------------------

View File

@@ -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,

View File

@@ -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());