Skip to content

Commit

Permalink
Ensure query extension only applies join / select onece per query
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastian-lenz committed Oct 10, 2019
1 parent 7ead34a commit d4cef3b
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/foreignField/ForeignFieldQueryExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use craft\elements\db\ElementQueryInterface;
use craft\helpers\ArrayHelper;
use craft\helpers\Db;
use craft\helpers\Json;
use Exception;
use Yii;

Expand Down Expand Up @@ -41,6 +42,16 @@ class ForeignFieldQueryExtension
*/
public $query;

/**
* @var bool
*/
private $_didAttachEagerLoad = false;

/**
* @var bool
*/
private $_didAttachJoin = false;


/**
* ForeignFieldQueryExtension constructor.
Expand Down Expand Up @@ -81,6 +92,9 @@ public function onAfterPrepare() {
* @return void
*/
protected function attachEagerLoad() {
if ($this->_didAttachEagerLoad) return;
$this->_didAttachEagerLoad = true;

$this->query->query->addSelect([
'field:' . $this->field->handle => $this->getJsonExpression(),
]);
Expand All @@ -90,6 +104,9 @@ protected function attachEagerLoad() {
* @return void
*/
protected function attachJoin() {
if ($this->_didAttachJoin) return;
$this->_didAttachJoin = true;

/** @var ActiveRecord $recordClass */
$recordClass = $this->field::recordClass();
$tableName = $recordClass::tableName();
Expand Down Expand Up @@ -219,7 +236,8 @@ static protected function enableEagerLoad(ElementQuery $query, ForeignField $fie
static protected function enableJoin(ElementQuery $query, ForeignField $field) {
$items = array_merge(
is_array($query->orderBy) ? $query->orderBy : [(string)$query->orderBy],
is_array($query->groupBy) ? $query->groupBy : [(string)$query->groupBy]
is_array($query->groupBy) ? $query->groupBy : [(string)$query->groupBy],
[Json::encode($query->where)]
);

foreach ($items as $item) {
Expand Down

0 comments on commit d4cef3b

Please sign in to comment.