Commit 78136d42 by Qiang Xue

Fixes #2880: filterByModels() should prefix key columns in a join query.

parent 9b8372d5
...@@ -356,12 +356,39 @@ trait ActiveRelationTrait ...@@ -356,12 +356,39 @@ trait ActiveRelationTrait
return $buckets; return $buckets;
} }
private function prefixKeyColumns($attributes)
{
if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
if (empty($this->from)) {
/** @var ActiveRecord $modelClass */
$modelClass = $this->modelClass;
$alias = $modelClass::tableName();
} else {
foreach ($this->from as $alias => $table) {
if (!is_string($alias)) {
$alias = $table;
}
break;
}
}
if (isset($alias)) {
foreach ($attributes as $i => $attribute) {
$attributes[$i] = "$alias.$attribute";
}
}
}
return $attributes;
}
/** /**
* @param array $models * @param array $models
*/ */
private function filterByModels($models) private function filterByModels($models)
{ {
$attributes = array_keys($this->link); $attributes = array_keys($this->link);
$attributes = $this->prefixKeyColumns($attributes);
$values = []; $values = [];
if (count($attributes) === 1) { if (count($attributes) === 1) {
// single key // single key
......
...@@ -402,6 +402,11 @@ class ActiveRecordTest extends DatabaseTestCase ...@@ -402,6 +402,11 @@ class ActiveRecordTest extends DatabaseTestCase
$this->assertEquals(3, $count); $this->assertEquals(3, $count);
$orders = $query->all(); $orders = $query->all();
$this->assertEquals(3, count($orders)); $this->assertEquals(3, count($orders));
// https://github.com/yiisoft/yii2/issues/2880
$query = Order::find(1);
$customer = $query->getCustomer()->joinWith('orders')->one();
$this->assertEquals(1, $customer->id);
} }
public function testJoinWithAndScope() public function testJoinWithAndScope()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment